zl程序教程

您现在的位置是:首页 >  前端

当前栏目

[!Typescript] Tips: Access deeper parts of objects and arrays

typescript and of access Tips Objects Arrays
2023-09-14 08:59:11 时间

Accessing object values and array members is MUCH more powerful in the type world than it is in the runtime world.

Passing a union... RETURNS a union!

interface ColorVariants {
  primary: "blue";
  secondary: "red";
  tertiary: "green";
}

type PrimaryColor = ColorVariants["primary"]; // "blue"
type NonPrimaryColor = ColorVariants["secondary" | "tertiary"]; // "red" | "green"
type EveryColor = ColorVariants[keyof ColorVariants]; // "blue" | "red" | "green"

type Letters = ["a", "b", "c"];
type AOrB = Letters[0 | 1]; // "a" | "b"
type Letter = Letters[number]; // "a" | "b" | "c"

interface UserRoleConig {
  user: ["view", "create", "update"];
  superAdmin: ["view", "create", "update", "delete"];
}

type Role = UserRoleConig[keyof UserRoleConig][number] // "view" | "create" | "update" | "delete"