I'm having issues following along with some of the examples in the official docs re: conditional types:
https://www.typescriptlang.org/docs/handbook/2/conditional-types.html
The docs contain this example:
interface IdLabel { id: number }
interface NameLabel { name: string }
type NameOrId<T extends number | string> = T extends number
? IdLabel
: NameLabel;
function createLabel<T extends number | string>(idOrName: T): NameOrId<T> {
throw "unimplemented";
}
// a is a NameLabel
let a = createLabel("typescript");
// b is an IddLabel
let b = createLabel(2.8);
So far, so good. The problem is if you actually try to implement the createLabel function, it doesn't typecheck:
function createLabel<T extends number | string>(idOrName: T): NameOrId<T> {
return typeof (idOrName) == "number" ? { id: idOrName } : { name: idOrName };
}
The exact error: Type '{ id: number; } | { name: string; }' is not assignable to type 'NameOrId<T>'. Type '{ id: number; }' is not assignable to type 'NameOrId<T>'.
My question is: why doesn't this work, and what's the right way to resolve it?
FWIW, there is a Stack Overflow post (~3 years old) that sort of addresses this issue, but the solution relies on adding additional casts/overloads that honestly seem to be unnecessary: