Ale*_*ara 5 generics casting typescript
TypeScript 2.8 添加了一个新的核心类型InstanceType,可用于获取构造函数的返回类型。
/**
* Obtain the return type of a constructor function type
*/
type InstanceType<T extends new (...args: any[]) => any> = T extends new (...args: any[]) => infer R ? R : any;
Run Code Online (Sandbox Code Playgroud)
这个特性非常好,但在使用抽象类时会崩溃,new根据 TypeScript 的类型系统没有声明。
起初,我认为我可以通过创建一个类似但限制较少的类型(移除extends new (...args: any[]) => any保护)来解决这个限制:
export type InstanceofType<T> = T extends new(...args: any[]) => infer R ? R : any;
Run Code Online (Sandbox Code Playgroud)
但是当传递一个抽象类时它也会崩溃,因为它无法推断返回类型并且默认为any. 这是一个使用模拟 DOM 作为示例的示例,并尝试进行类型转换。
abstract class DOMNode extends Object {
public static readonly TYPE: string;
constructor() { super(); }
public get type() {
return (this.constructor as typeof DOMNode).TYPE;
}
}
class DOMText extends DOMNode {
public static readonly TYPE = 'text';
constructor() { super(); }
}
abstract class DOMElement extends DOMNode {
public static readonly TYPE = 'text';
public static readonly TAGNAME: string;
constructor() { super(); }
public get tagname() {
return (this.constructor as typeof DOMElement).TAGNAME;
}
}
class DOMElementDiv extends DOMElement {
public static readonly TAGNAME = 'div';
constructor() { super(); }
}
class DOMElementCanvas extends DOMElement {
public static readonly TAGNAME = 'canvas';
constructor() { super(); }
}
// Create a collection, which also discards specific types.
const nodes = [
new DOMElementCanvas(),
new DOMText(),
new DOMElementDiv(),
new DOMText()
];
function castNode<C extends typeof DOMNode>(instance: DOMNode, Constructor: C): InstanceofType<C> | null {
if (instance.type !== Constructor.TYPE) {
return null;
}
return instance as InstanceofType<C>;
}
// Attempt to cast the first one to an element or null.
// This gets a type of any:
const element = castNode(nodes[0], DOMElement);
console.log(element);
Run Code Online (Sandbox Code Playgroud)
如果该构造函数是抽象类,有什么方法可以将变量转换为传递的构造函数的实例?
注意:我试图避免使用,instanceof因为 JavaScript 的instaceof问题很大(同一模块的 2 个不同版本具有不同的构造函数实例)。
您可以查询prototype抽象class的类型以获取其实例的类型。这并不要求类型具有new签名,仅当它具有prototype属性时。抽象类没有new签名,但它们有一个prototype属性。
这是它的样子
function castNode<C extends typeof DOMNode>(
instance: DOMNode,
Constructor: C
): C['prototype'] | null {
if (instance.type !== Constructor.TYPE) {
return null;
}
return instance;
}
Run Code Online (Sandbox Code Playgroud)
C['P']类型位置中的表达式称为索引访问类型。它是 type 中命名的属性的值P的类型 C。
| 归档时间: |
|
| 查看次数: |
3967 次 |
| 最近记录: |