简体   繁体   English

如何从 function 参数中获取计算属性名称的文字类型?

[英]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.

相关问题 如何从 class 属性(将 class 作为参数传递后)获取计算属性名称的文字类型? - How to get a literal type from a class property (after passing the class as argument) for a computed property name? 如何键入计算的属性名称? - How to type a computed property name? 类型文字中的计算属性名称必须引用类型为文字类型或“唯一符号”类型的表达式 - A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type 如何从函数参数中获取对象属性值作为类型 - How to get object property values as type from a function argument 接口中的计算属性名称必须引用其类型为文字类型或“唯一符号”类型的表达式 - A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type 打字稿:类型文字中的计算属性名称必须引用类型为文字类型或“唯一符号”的表达式 type.ts(1170) - Typescript : A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type.ts(1170) TypeScript 类型文字中的计算属性名称必须直接引用内置符号 - TypeScript A computed property name in a type literal must directly refer to a built-in symbol 如何在类型定义上部分使用计算所得的属性名称 - How to use partially the computed property name on a type definition 使用字符串文字作为计算属性名称的模板参数 - Using a string literal as a template parameter for a computed property name 打字稿将泛型约束为字符串文字类型以用于计算对象属性 - Typescript constrain generic to string literal type for use in computed object property
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM