2016-10-10 28 views
1

是否存在只允许列出值中的一个的typeScript?只允许列出值中的一个的类型Script

我想要什么:

typethatiwant Animals = ['cat', 'dog']; 
 

 
let myAnimal: Animals = 'cat'; // good 
 
myAnimal = 'dog'; // good 
 
myAnimal = 'hamster'; // error because 'hamster' not 'cat' or 'dog'

回答

4

的联合类型与字符串文字组合

type Animals = 'cat' | 'dog' 

看到它在the playground

+1

可以注意到,这取决于一个名为[字符串文字]的概念(https:// www .typescriptlang.org /文档/手册/先进types.html)。 – Alex

+1

@Alex是的!回答更新 –

+0

谢谢!这对我有用。 – ruvi