0

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!' );
Z0q
  • 1,689
  • 3
  • 28
  • 57
  • 4
    The type system does not exist at runtime. You cannot use runtime logic (an `if`) to interact with it. You need a concrete representation of this, so you can [have an array and get the type from it](https://stackoverflow.com/questions/45251664/typescript-derive-union-type-from-tuple-array-values) to be able to check it at runtime. – VLAZ Sep 22 '21 at 08:09

2 Answers2

2

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

playground

Medet Tleukabiluly
  • 11,662
  • 3
  • 34
  • 69
0

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`
}
Xetera
  • 1,390
  • 1
  • 10
  • 17