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

Kug*_*ran 5 arrays key typeof object typescript

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

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'],
   'random': ['random_1']
} // But this should throw an error

Run Code Online (Sandbox Code Playgroud)

Kok*_*ino 8

temp使a的类型为Partial

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

(顺便说一句。“动物”而不是“动物”)

Partial使每个字段都是可选的。

我建议使用 atype而不是数组:

const temp: Partial<{ [key in SomeArray]: string[] }> = {
    'animals': ['dog', 'cat']
}

type SomeArray = 'animals' | 'birds';
Run Code Online (Sandbox Code Playgroud)