Home > OS >  Typescript how to infer type from class constructor arguments
Typescript how to infer type from class constructor arguments

Time:12-29

I have a class definition that has typed arguments on the constructor. I want to reuse the argument type definition elsewhere without refactoring or extracting the definition from the class. How can I do this. below is an example with a GetProps<TBase> type that I was suggested but doesn't actually work. I expect the const bp definition to throw an error because it is missing the derp field which is defined in the constructor.

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'
};

CodePudding user response:

TypeScript includes a utility type for this: ConstructorParameters<Type>

TS Playground

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'
};
  • Related