[英]How can I specify that a type is an instance of a given class type in TypeScript?
我想創建一個Constructor
類型,它將 class 作為類型參數並返回其構造函數的簽名。
這將有助於在 class 上定義 static 屬性make
方法,該方法可以創建該 class 的實例,而不是使用new ClassInstance(...)
語句創建它。
這是我到目前為止所得到的:
type ClassConstructorArgs<T> = T extends { new (...args: infer A): any }
? A
: never;
type Constructor<T> = (...args: ClassConstructorArgs<T>) => T;
class Person {
constructor(public name: string, public age: number) {}
static make: Constructor<typeof Person> = (...args) => new Person(...args);
// ^^^^^^^^^^^^^^^^^^^
// Type 'Person' is missing the following properties from type 'typeof Person': prototype, make
}
問題是 static make
有一個錯誤: Type 'Person' is missing the following properties from type 'typeof Person': prototype, make
我知道這是因為我的Constructor
類型錯誤, class T
的構造函數不返回 class T
本身,而是T
的實例。
但是我不知道如何表達Constructor
返回T
的實例而不是 class T
本身。 這在 TypeScript 中是否可行?
Typescript 具有ConstructorParameters和InstanceType的內置實用程序:
type Constructor<T extends new (...args: any) => any> =
(...args: ConstructorParameters<T>) => InstanceType<T>;
class Person {
constructor(public name: string, public age: number) {}
static make: Constructor<typeof Person> = (...args) => new Person(...args);
}
const p = Person.make('some name', 1); // p is of type Person
如果您想知道這些實用程序是如何定義的以及您的嘗試有什么問題,請查看 go:
type ConstructorParameters<T extends new (...args: any) => any> =
T extends new (...args: infer P) => any ? P : never;
type InstanceType<T extends new (...args: any) => any> =
T extends new (...args: any) => infer R ? R : any;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.