2017-06-12 81 views
2

我现在有两个字符串数组,并包含相同字符串的字符串字面联合类型:打字稿数组字符串字面型

const furniture = ['chair', 'table', 'lamp']; 
type Furniture = 'chair' | 'table' | 'lamp'; 

我都在我的应用程序所需要的,但我想保持我的代码干。那么有什么办法可以从另一个方面推断出来吗?

我基本上想说一些像type Furniture = [any string in furniture array]这样的东西,所以没有重复的字符串。

回答

0

唯一adjustement我建议是使const保证与该类型兼容,就像这样:

type Furniture = 'chair' | 'table' | 'lamp'; 

const furniture: Furniture[] = ['chair', 'table', 'lamp']; 

这会给你一个警告,你应该做一个拼写错误的阵列中,或添加未知项目:

// Warning: Type 'unknown' is not assignable to furniture 
const furniture: Furniture[] = ['chair', 'table', 'lamp', 'unknown']; 

唯一的情况是,这不会帮助你,是阵列没有包含其中一个值的地方。