Depending on the type of parameter paramNameOrId
, the output type should switch between IdLabel
and NameLabel
. The following code block below works also as expected.
Main Code Block:
type IdLabel = { id: number };
type NameLabel = { name: string };
type NameOrIdType<T extends number | string> = T extends number
? IdLabel
: NameLabel;
function createLabel<T extends number | string>(
paramNameOrId: T,
): NameOrIdType<T> {
const nameOrId =
typeof paramNameOrId === 'string'
? { name: paramNameOrId }
: { id: paramNameOrId };
return nameOrId;
}
let a = createLabel('typescript'); // { name: 'typescript' }
let b = createLabel(4.1); // { id: 4.1 }
Problem:
Only the TypeSystem of TypeScript screams and means:
Type { name: T & string; id?: undefined; } OR
{ id: T; name?: undefined; }
is not assignable to type 'NameOrIdType<T>'.
Type { name: T & string; id?: undefined; }
is not assignable to type 'NameOrIdType<T>'.ts(2322)
What is my mistake? What would be the proper implementation in this case?