英文:
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;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论