0

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.

3
  • I think you can't mix up typescript and javascript like that. if statement is related to the runtime and typescript runs before compiling Commented Feb 25, 2020 at 18:56
  • Maybe type CheeseType should be an enum CheeseType then? If it was an enum, I could get an array of the string values of CheeseType and see if myString is contained in the array, right? Commented Feb 25, 2020 at 19:06
  • 1
    If you want to use an array you could do something like this. You need to pick a runtime representation of the values to check though. Once you decide on that someone can suggest how to get the compiler to understand what you're doing. Commented Feb 25, 2020 at 20:05

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.