typescript 是否可以在文字而不是接口上使用“keyof”运算符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41947168/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:13:07  来源:igfitidea点击:

Is it possible to use `keyof` operator on literals instead of interfaces?

typescript

提问by Rick

I have an object literal such as the following (all properties are known at compile time):

我有一个对象文字,如下所示(所有属性在编译时都是已知的):

const foo = {
  "hello": "hola"
};

If foowere an interface rather than a variable, I could easily do something like

如果foo是一个接口而不是一个变量,我可以很容易地做类似的事情

/** THEORETICAL ONLY - Does not compile! */
function translate(input: keyof foo): string {
  return foo[input];
}

However, doing so with a variable does not work, since the compiler cannot find an interface with the name foo.

但是,使用变量这样做是行不通的,因为编译器找不到名称为 的接口foo

Does Typescript support keyofoperations on object literals whose values are known at compile time?

Typescript 是否支持keyof对编译时已知值的对象文字进行操作?

回答by Ryan Cavanaugh

keyofoperates on types, but foois a value. But the typeofoperator takes a value and produces its type, so you can use keyof typeof footo do this.

keyof对类型进行操作,但它foo是一个值。但是typeof运算符接受一个值并生成它的类型,因此您可以使用它keyof typeof foo来执行此操作。

Note that this only works if you haven't associated an interface with the object literal (thanks radicand).

请注意,这仅在您尚未将接口与对象文字相关联时才有效(感谢radicand)。

回答by Eric

a bit off, while i'm finding indexer key to literals, but put it here for future reference.

有点不对劲,虽然我正在寻找文字的索引器键,但把它放在这里以供将来参考。

const foo = {
  "hello": "hola"
};

let data: { [key in keyof typeof foo]:number} & { name: string, index: number }[] = [] as any;

data.foo = 1;
data[0] = {name:'foo', 1};