RecipesChapter 4: Generics

Mapping Types with Type Maps

Recipe 4.8 from The TypeScript Cookbook

function createElement<T extends keyof AllElements>(
  tag: T,
  props?: Partial<AllElements[T]>
): AllElements[T];
function createElement(tag: string, props?: Partial<HTMLElement>): HTMLElement {
  const elem = document.createElement(tag);
  return Object.assign(elem, props);
}
Open in TypeScript Playground →