“keyof typeof"是什么意思?在打字稿中是什么意思? [英] What does "keyof typeof" mean in TypeScript?

查看:40
本文介绍了“keyof typeof"是什么意思?在打字稿中是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:

向我解释 keyof typeof 在 TypeScript 中的含义

Explain to me what keyof typeof means in TypeScript

enum ColorsEnum {
    white = '#ffffff',
    black = '#000000',
}

type Colors = keyof typeof ColorsEnum;

最后一行相当于:

type Colors = "white" | "black"

但它是如何工作的?

我希望 typeof ColorsEnum 返回类似 Object" 的东西,然后 keyof Object" 不会做任何有趣的事情.但我显然错了.

I would expect typeof ColorsEnum to return something like "Object" and then keyof "Object" to not do anything interesting. But I am obviously wrong.

推荐答案

keyof 接受一个对象类型并返回一个接受任何对象键的类型.

keyof takes an object type and returns a type that accepts any of the object's keys.

type Point = { x: number; y: number };
type P = keyof Point; // type '"x" || "y"'

const coordinate: P = 'z' // Type '"z"' is not assignable to type '"x" | "y"'.

typeof 与 TypeScript 类型

typeof 在 javascript 对象上调用时的行为与在 typescript 类型上调用时的行为不同.

typeof with TypeScript types

typeof behaves differently when called on javascript objects, to when it is called on typescript types.

  • TypeScript 在调用时使用 javascript 的 typeof在运行时处理 javascript 值并返回 undefined"、object"、boolean"、number"、bigint"、string"、symbol"、function"之一;
  • TypeScript 的 typeof 在类型值上被调用,但可以也可以在类型表达式中调用 javascript 值.它还可以推断 javascript 对象的类型,返回更详细的对象类型.
  • TypeScript uses javascript's typeof when called on javascript values at runtime and returns one of "undefined", "object", "boolean", "number", "bigint", "string", "symbol", "function"
  • TypeScript's typeof is called on type values, but can also be called on javascript values when in a type expression. It can also infer the type of javascript objects, returning a more detailed object type.
type Language = 'EN' | 'ES'; 
const userLanguage: Language = 'EN';
const preferences = { language: userLanguage, theme: 'light' };

console.log(typeof preferences); // "object"
type Preferences = typeof preferences; // type '{language: 'EN''; theme: string; }'

因为第二个 typeofreferences 在类型表达式中,所以它实际上是 TypeScript 自己的 typeof 被调用,而不是 javascript 的.

Because the second typeof preferences is in a type expression it is actually TypeScript's own typeof that get called, and not javascript's.

因为 keyof 是我们将调用 TypeScript 的 typeof 版本的 TypeScript 概念.

Because keyof is a TypeScript concept we will be calling TypeScript's verion of typeof.

keyof typeof 将推断 javascript 对象的类型并返回其键的联合类型.因为它可以推断出键的确切值,所以它可以返回它们的 文字类型的联合 而不是仅仅返回字符串".

keyof typeof will infer the type of a javascript object and return a type that is the union of its keys. Because it can infer the exact value of the keys it can return a union of their literal types instead of just returning "string".

type PreferenceKeys = keyof typeof preferences; // type '"language" | "theme"'

这篇关于“keyof typeof"是什么意思?在打字稿中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆