简体   繁体   中英

TypeScript function to check if type is not assignable to custom type

For example I have type:

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

And I have some function like this:

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

Is there any solution to create this function?

If you use string enums instead you can achieve this more easily:

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

Writing this as an answer since I can't comment yet:

This is a solution but not exact that I asked. Simply because at this case I need to duplicate types into array.

In addition to what Howard wrote: You could create the type based on the array. That way you wouldn't have to type the fruits in the array AND the type.

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

Have you tried type-guards ?

Something like below:

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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