繁体   English   中英

TypeScript function 检查类型是否不可分配给自定义类型

[英]TypeScript function to check if type is not assignable to custom type

例如我有类型:

type Fruits = 'apple' | 'lemon' | 'orange';  

我有一些像这样的 function :

const validateFruit = (value): boolean => {
  /// return true if value has type Fruits
}

有什么解决方案可以创建这个 function?

如果使用字符串枚举,则可以更轻松地实现:

enum Fruits { apple = 'apple',  lemon = 'lemon',  orange = 'orange' }; 
const validateFruit = (value): value is Fruits => Fruits[value] !== undefined;

写这个作为答案,因为我还不能发表评论:

这是一个解决方案,但并不完全符合我的要求。 仅仅是因为在这种情况下我需要将类型复制到数组中。

除了霍华德写的:您可以根据数组创建类型。 这样您就不必在数组和类型中输入水果。

    const FRUITS_ARRAY = ['apple', 'lemon', 'banana'] as const
    type Fruits = typeof FRUITS_ARRAY[number]

您是否尝试过类型保护器

如下所示:

type Fruits = 'apple' | 'lemon' | 'orange';  

function isFruits(value: Fruits | any): value is Fruits {
    return ['apple', 'lemon', 'orange'].indexOf(value) > -1;
}

console.log(isFruits('dd'));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM