简体   繁体   English

TypeScript 中有没有办法直接从 object 的键创建新类型?

[英]Is there a way in TypeScript to create a new type directly from the keys of an object?

Is there a way in TypeScript to create a new type directly from the keys of an object? TypeScript 中有没有办法直接从 object 的键创建新类型? In the following example TypeScript correctly complains ( 'msg' refers to a value, but is being used as a type here. ) about msg referring to a value but I was wondering if there is a way to get this working without having to create a separate type definition?在下面的示例中,TypeScript 正确地抱怨( 'msg' refers to a value, but is being used as a type here. )关于 msg 指的是一个值,但我想知道是否有一种方法可以使它工作而不必创建一个单独的类型定义?

const msg = {okay: 'Okay', cancel: 'Cancel'};

function getMsg(id: keyof msg): string {
   return msg[id];
}

typeof gets a type from a value. typeof从值中获取类型。 Then you put keyof in front of that to get this slightly odd looking type:然后你把keyof放在它前面以获得这个看起来有点奇怪的类型:

const msg = {okay: 'Okay', cancel: 'Cancel'};

function getMsg(id: keyof typeof msg): string {
   return msg[id];
}

Playground 操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM