typescript - 在 TypeScript 中, "extends keyof"和 "in keyof"是什么意思?

标签 typescript keyof

在 TypeScript 中,一些类型是使用 extends keyof 定义的或 in keyof .我试图理解它们的意思,但到目前为止我没有成功。

我得到的是 keyof alone 返回一个联合类型,它具有所有名称作为可能值,这些值作为属性名称存在于您在 keyof 之后指定的类型上.

type T = keyof string;

T因此相当于 startsWith | endsWith | trim | substring | ... .

这是正确的吗?

现在,如果我试着想一想 extends keyofin keyof意思是,我的直觉是这样的:

  • extends keyof是从 T 派生的任何类型,即它具有所有这些可能的值,但可能更多。
  • in keyof是从 T 获取值的任何类型,但不一定全部(有可能,但可能更少)。

所以,从这个 POV extends keyof会描述一个 >=关系,in keyof会描述一个 <=关系。这样对吗?如果不是,那什么是正确的?

最佳答案

对于任何类型 T , keyof TT 的已知公共(public)属性名称的联合.

例子:

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

type PersonKeys = keyof Person; // "age" | "name"

您的假设 keyof string产量 startsWith | endsWith | trim | ...因此是正确的。您可以在 lookup type release notes 中了解更多信息.

扩展keyof

extends ,在这种情况下,用于 constrain the type of a generic parameter .示例:

<T, K extends keyof T>

K因此只能是 T 的公共(public)属性名称.它与扩展类型或继承无关,与extending interfaces相反.

extends keyof 的用法可能是以下内容:

function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

const person: Person = {
  age: 22,
  name: "Tobias",
};

// name is a property of person
// --> no error
const name = getProperty(person, "name");

// gender is not a property of person
// --> error
const gender = getProperty(person, "gender");

除了 documentation on index types , 我找到了 this helpful article .

在关键字中

in当我们定义 index signature 时使用我们想用字符串、数字或符号文字的联合来键入。结合keyof我们可以使用它来创建一个所谓的映射类型,它重新映射原始类型的所有属性。

in keyof 的用法可能是以下内容:

type Optional<T> = { 
  [K in keyof T]?: T[K] 
};

const person: Optional<Person> = {
  name: "Tobias"
  // notice how I do not have to specify an age, 
  // since age's type is now mapped from 'number' to 'number?' 
  // and therefore becomes optional
};

除了 documentation on mapped types ,我又一次找到了this helpful article .

Fun fact: The Optional<T> type we've just built has the same signature as the official Partial<T> utility type!

关于typescript - 在 TypeScript 中, "extends keyof"和 "in keyof"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57337598/

相关文章:

Typescript:推断嵌套 keyof 属性的类型

javascript - 取一个输入的一维数组[1,2,3,4],输出除当前索引[24,12,8,6]之外的整数的乘积;

enums - TypeScript 枚举之外的值没有错误

TypeScript:如何为具有许多相同类型的键和相同类型的值的对象创建接口(interface)?

javascript - 使用 keyof 之类的方法进行 TypeScript 数组类型转换

javascript - 映射对象键时使通用对象可选(在 keyof 中)

typescript - 为什么 Typescript 不能在赋值中使用泛型的 keyof 类型并将其泛化为字符串?

Typescript - 如何在 switch 语句中缩小泛型类型的类型可能性?

node.js - 如何使用 TypeScript 在 Express 中输入 app.get ('/events' , (req, res)

typescript - 类型 'any' 不能分配给类型 'never' 试图用变量设置 Object 属性时 keyof ObjectType