Home > OS >  Typescript With Generics Property 'input' does not exist on type 'T'
Typescript With Generics Property 'input' does not exist on type 'T'

Time:11-03

I'm using typescript 4.8, I have an error on my types that I really don't understand.

function normalize<T = (InputData | Omit<InputData, "output">)>(
    company: T
): any {
    console.log(company.input.numberOfWorker);
}

This will show: Property 'input' does not exist on type 'T'., But input does exist on InputData.

But the thing is, if I do that it works:

function normalize(
    company: InputData | Omit<InputData, "output">
):any {
    console.log(company.input.numberOfWorker);
}

and for me that the same thing no ? since T is meant to be equal to InputData or the Omit

Thanks a lot if you can explain me

CodePudding user response:

Problem

<T = (InputData | Omit<InputData, "output">)>

This only assigns a default type to T. However a consumer of this function could pass in any type, which may not be the same shape as InputData and therefore does not have the input property, into the type parameter. For example:

normalize<string>("");

TypeScript Playground

Solution

You want to add a constraint to T. This is done using the extends keyword like so:

<T extends (InputData | Omit<InputData, "output">)>

TypeScript Playground

Further reading

  • Related