类型注解
2023年06月27日
一、构造函数
1.1 构造函数体
-
通用构造函数类型注解
class Person {
public name: string;
public age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
type ConstructorType<T> = new (...args:any[]) => T;
const PersonConstructor:ConstructorType<Person> = Person; -
特定构造函数类型注解
-
通过 new 关键字对特定构造函数类型注解
class Person {
public name: string;
public age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
type PersonConstructorType = new (name:string,age:number) => Person;
const PersonConstructor:PersonConstructorType = Person; -
通过 typeof 关键字对特定构造函数类型注解
class Person {
public name: string;
public age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
const PersonConstructor:typeof Person = Person;
-
1.2 构造函数参数
-
通过 infer P 获取构造函数参数,进而对构造函数参数进行类型注解
class Person {
public name: string;
public age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
type ConstructorType = new (...args: any[]) => any;
type ConstructorTypeT<T> = new (...args: any[]) => T;
type ConstructorParamsType<T extends ConstructorType> = T extends new (...args: infer P) => any ? P : any;
function createInstance<T>(constructor: ConstructorTypeT<Person>, ...args: ConstructorParamsType<typeof Person>) {
return new constructor(...args)
}
const person = createInstance<Person>(Person,'柏拉图',23)