Reputation: 13
Let's say I have a type
defined like so: type CheeseType = 'Cheddar' | 'Pepperjack' | 'Gouda'
.
Given a string
, how can I determine whether that string
value is in the CheeseType
list?
I'm imagining something like if (myString is CheeseType)
or if (myString in CheeseType)
, but these don't seem to work.
Upvotes: 0
Views: 69
Reputation: 31815
This type CheeseType = 'Cheddar' | 'Pepperjack' | 'Gouda'
has absolutely no representation in JavaScript and is not emulated in any way. You can figure it out by copy/pasting it in https://www.typescriptlang.org/play.
So you won't be able to check the type at runtime. The only purpose of type
is to prevent your code from compiling in case of type misuse, so you don't have to run the code to notice obvious mistakes.
You can use enum
which has a representation in JavaScript (an object) and will allow you to make runtime type checking.
Upvotes: 1