我需要进行此比较:
type Type<T extends string, S extends string> = T extends S ? S extends T ? true : false : never;
function getElement<T extends string, S extends string = string>(s: S) {
let value: unknown;
return value as Type<T, S>;
}
getElement<'a'>('a');
但是该函数已返回错误,即使值相同。在这种情况下,通用类型t变为字符串字面,类型s变成类型字符串,比较变得失败。在这种情况下,如何知道通用类型的字面类型?
这是此Web-component中的getElement方法的转角案例。我正在尝试根据选择器参数来推断返回元素的类型,这也可以是像'''''d'title__big'(在这种情况下,我需要指向type type t type t typetygeTygetElement('title __big')=>htmldivelement并获得返回的返回-HTMLDIVIVELMENT-等等。但是,如上所述,通用类型不断不同。是否可以捕获<'div'>getElement方法参数的文字类型并推断返回的类型?也许还有另一种解决这个问题的方法吗?。
type ElementType<
T extends string,
S extends string,
E extends Element,
> = T extends keyof HTMLElementTagNameMap
? S extends keyof HTMLElementTagNameMap
? HTMLElementTagNameMap[S] extends HTMLElementTagNameMap[T]
? HTMLElementTagNameMap[S]
: never
: unknown
: E;
class Component extends HTMLElement {
constructor(shadowrootmode: 'closed' | 'open' = 'open') {
super();
this.attachShadow({ mode: shadowrootmode });
}
protected get shadowDom() {
if (!this.shadowRoot) throw new Error('The shadow root is not attached');
return this.shadowRoot;
}
protected getElement<T extends string, S extends string = string>(selector: S) {
const element = this.shadowRoot?.querySelector(`${selector}`);
if (!element) throw new Error('Element not found.');
return element as ElementType<T, S, typeof element>;
}
test() {
this.getElement<'a'>('a').click = () => 3;
}
}
export { Component };
游乐场在这里。
通过方式,出于相同的原因,类似的超载给出了相同的结果。
protected getElement<
T extends keyof HTMLElementTagNameMap,
S extends keyof HTMLElementTagNameMap = keyof HTMLElementTagNameMap,
>(
selector: S,
): HTMLElementTagNameMap[T] extends HTMLElementTagNameMap[S] ? HTMLElementTagNameMap[T] : never;
thanks为参加人物。
为什么只是不使用这样的使用:
Playground