javascript - TypeScript 函数用于检查类型是否不可分配给自定义类型
例如,我已经输入了:
type Fruits = 'apple' | 'lemon' | 'orange';
我有一个这样的函数:
const validateFruit = (value): boolean => {
/// return true if value has type Fruits
}
有没有办法创建这个功能?
答案#1
如果你改用字符串枚举,你可以更容易地实现这一点:
enum Fruits { apple = 'apple', lemon = 'lemon', orange = 'orange' };
const validateFruit = (value): value is Fruits => Fruits[value] !== undefined;
答案#2
写下这个作为回答,因为我还不能评论:
这是一个解决方案,但不是我所要求的确切方案。只是因为在这种情况下,我需要将类型复制到数组中。
除了霍华德写的内容之外:你可以基于数组创建类型。这样你就不必在数组和类型中都输入水果了。
const FRUITS_ARRAY = ['apple', 'lemon', 'banana'] as const
type Fruits = typeof FRUITS_ARRAY[number]
