繁体   English   中英

从打字稿数组中的字符串派生键以定义对象属性名称

[英]Derive keys from strings in array in typescript to define object property names

我想定义一个对象中的键匹配二维数组的第一项。

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
}

游乐场链接

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM