简体   繁体   English

Typescript 如何从 class 构造函数 arguments 推断类型

[英]Typescript how to infer type from class constructor arguments

I have a class definition that has typed arguments on the constructor.我有一个 class 定义,它在构造函数上输入了 arguments 。 I want to reuse the argument type definition elsewhere without refactoring or extracting the definition from the class.我想在其他地方重用参数类型定义,而不重构或从 class 中提取定义。 How can I do this.我怎样才能做到这一点。 below is an example with a GetProps<TBase> type that I was suggested but doesn't actually work.下面是我建议但实际上不起作用的GetProps<TBase>类型的示例。 I expect the const bp definition to throw an error because it is missing the derp field which is defined in the constructor.我希望const bp定义会引发错误,因为它缺少构造函数中定义的derp字段。

type GetProps<TBase> = TBase extends new (props: infer P) => any ? P : never

class Bro {
    bro: string = 'cool'
    cool: string = 'lol'
    constructor(props: {bro: string, cool: string, derp: string}){   
        this.bro = props.bro;
        this.cool = props.cool;
    }
}

const bp : GetProps<Bro> = {
    bro: 'lol',
    cool: 'wut'
};

TypeScript includes a utility type for this: ConstructorParameters<Type> TypeScript 为此包括一个实用程序类型: ConstructorParameters<Type>

TS Playground TS游乐场

const bp: ConstructorParameters<typeof Bro>[0] = {
/*    ^^
Property 'derp' is missing in type '{ bro: string; cool: string; }'
but required in type '{ bro: string; cool: string; derp: string; }'.(2741) */
  bro: 'lol',
  cool: 'wut'
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM