#Type interence

3 messages · Page 1 of 1 (latest)

noble holly
#

I have this code

type Union = string | number | { id: number } | { id: string };

const getValue = <T extends Union>(item: T) => {
    return typeof item === "object" 
        ? item.id // correctly inferred as number | string
        : item; // inferred as T, not as number | string
};

And it seems to me that the return type of getValue should be inferred to be number or string, but it's inferred as number | string | T.

I have a feeling that there is a way to extend the Union type to break the contract, but I can't think of a way how...

frank vine
#

arguably the typeof item === "object" check could eliminate this, but i think the type-theory reason this happens is because stuff like this is allowed:

type WackyString = string & { id: number }
declare const item: WackyString
getValue<WackyString>(item)
noble holly
#

Yes, @frank vine - tnx, that's what I was missing. (of course, removing the generic from the function, fixes the interence)