Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Typescript的keyof的作用是什么 #153

Open
su37josephxia opened this issue Mar 15, 2022 · 4 comments
Open

Typescript的keyof的作用是什么 #153

su37josephxia opened this issue Mar 15, 2022 · 4 comments

Comments

@su37josephxia
Copy link
Owner

No description provided.

@zcma11
Copy link

zcma11 commented Mar 16, 2022

keyof 可以得到对象上的 key 组成的联合类型。配合 extends 可以约束泛型, keyof 自身得到的类型也能约束类型。

function foo<T, K extends keyof T>(obj: T, key: K) {}

interface bar {
  age: number
  name: string
}

keyof bar // 'age' | 'name'

@chunhuigao
Copy link

  • keyof操作符可以用于获取某种类型的所有键,其返回类型是联合类型
  • keyof操作符可以用于操作类
    总结:keyof操作符对枚举类型,返回枚举类型属性,对类操作,返回类的属性

@7TingYu
Copy link

7TingYu commented Mar 16, 2022

keyof 操作符能让你捕获一个类型的键。

任何类型 T, keyof T的结果为 T上已知的公共属性名的联合。

@miracle-dx
Copy link

miracle-dx commented Mar 17, 2022

可以通过keyof操作符在类型上下文中得到引用变量或者属性的类型。

let s = "hello";
let n: typeof s;    // n类型为string

如果是函数,结合预定义类型ReturnType,可以得到它的返回类型

function f () {
   return  { x: 3, y: 3 }
}
type P = ReturnType<typeof f>   // type P = { x: number, y: number }

如果是对象,通过typeof可以得到对象上的key组成的联合类型

interface bar {
  age: number;
  name: string;
}
type P = keyof bar   //type P =  'age' | 'name'

配合extends关键字,可以实现对泛型的约束

function pluck<T, K extends keyof T>(o: T, names: K[]): T[K][] {
  return names.map((n) => o[n]);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants