【问题标题】:A question in Type inference in conditional types条件类型中的类型推断中的一个问题
【发布时间】:2020-03-18 08:20:15
【问题描述】:
type CtorParamsType<T> = T extends {
    new(...args: infer U);
} ? U : any;

class MyType {
    constructor(name: string, age: number) {

    }
}

type T1 = CtorParamsType<MyType> //any
type T2 = CtorParamsType<{ new(name: string, age: number); }> //[string, number]

在这个示例中,我预计 T1 和 T2 将具有相同的类型。为什么它们不同?

【问题讨论】:

    标签: typescript types type-inference


    【解决方案1】:

    您要查找的类型已经存在,称为ConstructorParameters

    您的类型也可以,唯一的问题是 MyType 是实例类型。你想要类类型的构造函数参数,你可以使用typeof MyType访问它

    
    class MyType {
        constructor(name: string, age: number) {
    
        }
    }
    
    type T1 = ConstructorParameters<typeof MyType> // [string, number]
    type T2 = ConstructorParameters<{ new(name: string, age: number): any }> // [string, number]
    
    

    Playground Link

    【讨论】:

    • MyType 是实例类型吗?
    • @wude,是的,这意味着它是类实例的类型(即表达式new MyType(....)的类型。类本身,在JS中您只需使用类名(即MyClass.staticMehtodconst cls = MyClass),是typeof MyClass
    • 如何理解“typeof MyClass”。
    猜你喜欢
    • 2018-10-20
    • 2020-10-14
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 2023-03-17
    • 2016-04-04
    • 1970-01-01
    相关资源
    最近更新 更多