简体   繁体   English

如何键入计算的属性名称?

[英]How to type a computed property name?

const foobar = <T extends 'a' | 'b' | 'c'>(name: T) => ({
  [name]: name,
  [`${name}Copy`]: name
})

const result = foobar('a') // typeof result is { [x: string]: "a" }

How to type a computed property name here?如何在此处键入计算的属性名称?

I want foobar('a') to return { a: "a", aCopy: "a" } instead of { [x: string]: "a" } .我希望foobar('a')返回{ a: "a", aCopy: "a" }而不是{ [x: string]: "a" }

You can explicitly tell typescript about the return type您可以明确告诉 typescript 关于返回类型

const foobar = <T extends 'a' | 'b' | 'c'>(name: T) => ({ [name]: name }) as Record<T, T>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在类型定义上部分使用计算所得的属性名称 - How to use partially the computed property name on a type definition 如何从 function 参数中获取计算属性名称的文字类型? - How to get a literal type from a function argument for a computed property name? 计算的属性名称不可分配给记录类型 - Computed property name is not assignable to Record type 如何从 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 set type when computed property is used? 如何在接口中使用字符串枚举类型作为计算属性名称? - How can I use a string enum type as a computed property name in an interface? 如何在新组合 API 中键入计算属性? - How to type a computed property in the new composition API? TypeScript - 计算属性名称的类型必须为“字符串”、“数字”、“符号”或“任意” - TypeScript - A computed property name must be of type 'string', 'number', 'symbol', or 'any' 类型文字中的计算属性名称必须引用类型为文字类型或“唯一符号”类型的表达式 - A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type 接口中的计算属性名称必须引用其类型为文字类型或“唯一符号”类型的表达式 - A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM