Recipes
›
Chapter 5: Conditional Types
Managing Complex Function Signatures
Recipe 5.1 from
The TypeScript Cookbook
function createLabel<T extends number | string | StringLabel | NumberLabel>(
input: T
): GetLabel<T>;
function createLabel(
input: number | string | StringLabel | NumberLabel
): NumberLabel | StringLabel {
if (typeof input === "number") {
return { id: input };
} else if (typeof input === "string") {
return { name: input };
} else if ("id" in input) {
return { id: input.id };
} else {
return { name: input.name };
}
}