构造函数参数类型
构造函数参数类型 ConstructorParameters<T>
ts
class User {
constructor(public name: string, public age: number) {}
}
type MyConstructorParameters<T extends abstract new (...args: any) => any> =
T extends abstract new (...args: infer P) => any ? P : never;
// 构造函数参数类型
type userContructorType = ConstructorParameters<typeof User>; // [name: string, age: number]
/**
*
*/
class Book {
title: string;
content: string;
constructor(title: string, content: string) {
this.title = title;
this.content = content;
}
}
class CreateInstance<T extends new (...args: any) => any> {
private instanceConstructor: T;
constructor(classConstructor: T) {
this.instanceConstructor = classConstructor;
}
getInstance(...args: ConstructorParameters<T>): InstanceType<T> {
return this.instanceConstructor(...args);
}
}
const book = new CreateInstance(Book);
book.getInstance("title", "content"); // Book { title: 'title', content: 'content' }实例对象类型 InstanceType<T>
ts
class Book {
title: string;
content: string;
constructor(title: string, content: string) {
this.title = title;
this.content = content;
}
}
type instanceType = InstanceType<typeof Book>; // Book获取异步接口返回的 Promise 类型的泛型 Awaited<T>
ts
interface User {
name: string;
age: number;
address: string;
}
async function getUser(): Promise<User> {
const data = await fetch("https://jsonplaceholder.typicode.com/users/1");
return data.json();
}
type UserType = Awaited<ReturnType<typeof getUser>>; // User{ name: string; age: number; address: string; }
const user: UserType = {
name: "John",
age: 30,
address: "New York",
};