我想在对象中定义键匹配2维数组的第一项。
export const ProductInfos = [
["description", "Description"],
] as const
type ProductInfoTypes = typeof ProductInfos[number][0]
export type Product = {
id: string
//[key in typeof ProductInfos[number][0]]: string
}
因此,这里Product
应该以接受字符串的属性“ description”结尾。
但是我[key in typeof ProductInfos[number][0]]: string
不编译
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)
A computed property name must be of type 'string', 'number', 'symbol', or 'any'.ts(2464)
The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter.ts(2361)
您可以使用内置的类型映射器Record
和交集类型,如下所示:
export const ProductInfos = [
["description", "Description"],
] as const
type ProductInfoTypes = typeof ProductInfos[number][0]
type ProdcutDescription = Record<ProductInfoTypes,string>
type Base = {
id: string
}
type Product = Base & ProdcutDescription
const product : Product ={
id:"asdsa",
description : "as" //ok
foo:"ere" // error
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句