为什么 TypeScript 不能直接使用字符串字面量来组合对象类型?

huangapple go评论56阅读模式
英文:

Why can't typescript use string literals directly to compose an object type?

问题

以下是要翻译的内容:

我有一个文字类型,我想用它来组合一个对象的类型,而这个文字类型被用作对象的键,但是上面的写法不起作用。为什么上面会出错?

英文:

I have a literal type that I want to use to compose an object's type, and this literal type is used as a key for the object, but the following writing does not work correctly.

type k = "name";
type v = string;

type obj = {
    [k]: v
}

Why does the above get an error?

答案1

得分: 1

要将字面量用作键,您应该使用[映射类型](https://www.typescriptlang.org/docs/handbook/2/mapped-types.html):

type obj = {
[K in k]: v;
};


结果:

type obj = {
name: string;
}

英文:

To use literals as keys you should use mapped types:

type obj = {
  [K in k]: v;
};

Result:

type obj = {
    name: string;
}

huangapple
  • 本文由 发表于 2023年7月24日 16:43:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76752763.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定