【发布时间】:2022-01-13 14:26:04
【问题描述】:
我正在尝试创建一个类或构造函数,我指定了一个值列表,用于其中一个方法的类型。
作为一个例子,我有这个代码。
const MyAnimal = function (animal: string[]) {
type Animal = typeof animal[number]
this.getAnimal = (url: Animal) => {
console.log(url)
}
}
const animalTest = new MyAnimal(['sheep', 'dog', 'cat'])
// I would like this to fail as 'mouse' is not part of the array ['sheep', 'dog', 'cat']
animalTest.getAnimal('mouse')
我希望 getAnimal 具有 'sheep' | 'dog' | 'cat' 类型,并且如果我添加不同的内容,智能感知会警告我
这可能吗?
【问题讨论】:
标签: javascript typescript