小编Kug*_*ran的帖子

如何使对象的键是数组的值类型(值应该是可选的而不是强制的)

我面临着一种情况,我需要给对象的键是另一个数组的值,就像这样

const temp: { [key in typeof someArray[number] ]: string[] } = {
   'animal': ['dog', 'cat']
} // ERROR - missing the following properties from type birds ...  

const someArray = [ 'animals', 'birds' ] as const;  

Run Code Online (Sandbox Code Playgroud)

这使得临时对象应该包含数组内所有值的键。但是,我需要使值成为可选的,即,如果有任何键,那么它需要是数组的值之一,如果某些值不作为键存在,那么应该没有问题

const temp: { [key in typeof someArray[number] ]: string[] } = {
   'animal': ['dog', 'cat']
} // This shouldn't considered as an error 

const temp: { [key in typeof someArray[number] ]: string[] } = {
   'animal': ['dog', 'cat'], …
Run Code Online (Sandbox Code Playgroud)

arrays key typeof object typescript

5
推荐指数
1
解决办法
5859
查看次数

标签 统计

arrays ×1

key ×1

object ×1

typeof ×1

typescript ×1