type TestR = ReturnType<typeof changeName> // 返回字面量类型 type TestR = string | number type TestP = Parameters<typeof changeName> // 返回元祖类型 type TestP = [obj: Member, name: keyof Member]
// 现在看看如何模拟ReturnType/Paramters
type MockReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any; type TestMockR = MockReturnType<typeof changeName> const TestMOckReturn: TestMockR = '111' // is ok /** * 1.范型部分的 函数类型表示(...args: any) => any * 2.正文中的函数类型表示 (...args: any) => any * 3.infer 后面带出一个新的类型 */
type MockParameters<T extends (...args: any) => any> = T extends (...args: infer P) => any ? P : never; type testMockP = MockParameters<typeof changeName> // [obj: Member, name: "name" | "age"] const TestMock: testMockP =[{age: 22, name: 'cccc'}, 'name'] // is ok /** * 1.范型部分跟ReturnType一样 * 2.最难理解的是正文的推断部分 * 3.(...args: infer P) => any ? P : never */
class Cpp { private name private age constructor({name, age}: Member) { this.name = name this.age = age } getName() { return this.name } } const ClassCppInstance = new Cpp({ name: 'chendap', age: 30 }) export type TTestClassCpp = InstanceType<typeof Cpp> type MockAge = TTestClassCpp['age'] // type MockAge = number type MockGetName = TTestClassCpp['getName'] // type MockGetName = () => string
// 现在看看如何实现一个InstanceType
type MockIntanceType<T extends abstract new (...args: any) => any> = T extends abstract new (...args: any) => infer R ? R : any; type MockTestCpp = MockIntanceType<typeof Cpp> type MockAge2 = MockTestCpp['age'] // type MockAge = number type MockGetName2 = MockTestCpp['getName'] // type MockGetName = () => string
type TConstructor = ConstructorParameters<typeof Cpp> // type TConstructor = [Member] // 看看如何实现一个ConstructorParameters type MockConstructorParameters<T extends abstract new (...ars: any) => any> = T extends abstract new (...args: infer P) => any ? P : never;
type UserPromise = Promise<UserCpp> // 这个类型表示一个返回值类型为 User的 Promise类型。我们想把 User这个类型从这个已知的函数中提取出来,应当使用 infer关键字 type UnPromisify<T> = T extends Promise<infer V> ? V : never; type InferUser = UnPromisify<UserPromise>