typescript pick code example

Example 1: typescript keyof

interface Person {
  name: string;
  age: number;
  location: string;
}

type K1 = keyof Person; // "name" | "age" | "location"
type K2 = keyof Person[]; // "length" | "push" | "pop" | "concat" | ...
type K3 = keyof { [x: string]: Person }; // string

Example 2: typescript record

interface PageInfo {
  title: string;
}

type Page = "home" | "about" | "contact";

const nav: Record<Page, PageInfo> = {
  about: { title: "about" },
  contact: { title: "contact" },
  home: { title: "home" },
};

nav.about;
//   ^ = Could not get LSP result: v.a>bTry

Example 3: typescript pick

type TodoPreview = Pick<Todo, "title" | "completed">;

Example 4: typescript utility types merge interfaces

interface A {
    x: string
}

interface B extends Omit<A, 'x'> {
  x: number
}

Tags:

Misc Example