RecipesChapter 12: Type Development Strategies

Deciding Whether to Use Function Overloads or Conditional Types

Recipe 12.7 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 };
  }
}
Open in TypeScript Playground →