Skip to content

keyof 和类型访问 #10

@astak16

Description

@astak16

keyof

可以把 keyof 简单的理解为相遍历,把遍历的结果作为联合类型返回。

用官网的例子讲解,首先定义一个 Person 接口

interface Person {
  name: string;
  age: number;
  location: string;
}
  1. 遍历 Person 接口的属性,将得到的值是 nameagelocation 的联合类型

    type K1 = keyof Person; // "name" | "age" | "location"
  2. Person[] 是个数组,遍历的是数组的属性,得到的就是数组属性的联合类型

    type K2 = keyof Person[]; // "length" | "push" | "pop" | "concat" | ...
  3. 就是一个对象,对象的 keystring 类型,所以得到 string ,但为什么是 stringnumber 的联合类型,还不太清楚。

    如果把 string 换成了 number ,那么得到的结果是 nubmer

    type K3 = keyof { [x: string]: Person }; // string | number
    type K4 = keyof { [x: number]: Person }; // number

类型访问

  1. 类型也可以通过访问的形式得到, Person["name"] 因为 namestring 所以得到 string

    type P1 = Person["name"]; // string
  2. namestringagenumber ,得到 stringnumber 的联合类型

    type P2 = Person["name" | "age"]; // string | number
  3. stringcharAt 是函数,得到 charAt 函数类型

    type P3 = string["charAt"]; // (pos: number) => string
  4. stringpush 是函数,得到 push 函数类型

    type P4 = string[]["push"]; // (...items: string[]) => number
  5. 访问数组的第一项,类型是 string

    type P5 = string[][0]; // string

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions