[英]How to get a literal type from a function argument for a computed property name?
please consider the following code:请考虑以下代码:
const fn = (name: string) => {
return { [name]: "some txt" };
};
const res = fn("books"); // books or any other string
TS recognizes res
as the following type: TS 将
res
识别为以下类型:
const res: {
[x: string]: string;
}
I'd like TS to know that res
has a property books
我想让 TS 知道
res
有一个属性books
const res: {
books: string;
}
I tried many things but nothing seems to work.我尝试了很多东西,但似乎没有任何效果。 Is it possible at all?
有可能吗? Is it a known issue?
这是一个已知问题吗?
You have to create a generic function like this:你必须像这样创建一个通用的 function :
const fn = <T extends string>(name: T): { [key in T]: string } => {
return { [name]: "some txt" } as any;
};
const res = fn("books");
It seems like a bug in TypeScript that it doesn't allow such things, that's why you need the as any
.这似乎是 TypeScript 中的一个错误,它不允许这样的事情,这就是你需要
as any
的原因。 See here for an interactive example.有关交互式示例,请参见此处。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.