简体   繁体   中英

Typescript: Determining whether a string is in a string union type

Let's say I have a type defined like so: type CheeseType = 'Cheddar' | 'Pepperjack' | 'Gouda' type CheeseType = 'Cheddar' | 'Pepperjack' | 'Gouda' 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.

This type CheeseType = 'Cheddar' | 'Pepperjack' | 'Gouda' type CheeseType = 'Cheddar' | 'Pepperjack' | 'Gouda' 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.

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