How do I check whether a string exists in a type?
For example
type Fruit = 'Apple' | 'Banana' | 'Orange';
const myFruit = 'Banana';
if( myFruit /* is in */ Fruit )
console.log( 'myFruit is a fruit!' );
CodePudding user response:
Don't mix type
and value
Fruit is type
type Fruit = 'Apple' | 'Banana' | 'Orange';
myFruit is value
const myFruit = 'Banana';
There is no Fruit when typescript compiles to javascript
CodePudding user response:
If you want to check whether a value you're looking for exists in a union type, you can't directly do that as others have mentioned since types don't exist in runtime in TypeScript. But you can use a tuple to "represent" that type in runtime and derive the union type you're looking for out of it like this.
// making sure `allFruits` is interpreted as a tuple of
// string literals insted of an array of strings
const allFruits = ["Apple", "Banana", "Orange"] as const;
type Fruit = typeof allFruits[number]; // 'Apple' | 'Banana' | 'Orange'
const myFruit = 'Banana';
if(allFruits.includes(myFruit))
console.log('myFruit is a fruit!');
If the goal is to be able to narrow the string
into a type Fruit
through the if statement, you can use a Type Guard to infer that.
function isFruit(input: string): input is Fruit {
return allFruits.includes(input as Fruit);
}
let maybeFruit = "Banana";
// type of `maybeFruit` here is `string`
if (isFruit(maybeFruit)) {
// type of `maybeFruit` here is `Fruit`
}