簡體   English   中英

如何指定類型是 TypeScript 中給定 class 類型的實例?

[英]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 具有ConstructorParametersInstanceType的內置實用程序:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM