简体   繁体   English

打字稿:确定字符串是否属于字符串联合类型

[英]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'假设我有一个这样定义的typetype CheeseType = 'Cheddar' | 'Pepperjack' | 'Gouda' 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?给定一个string ,如何确定该string值是否在CheeseType列表中?

I'm imagining something like if (myString is CheeseType) or if (myString in CheeseType) , but these don't seem to work.我想像if (myString is CheeseType)if (myString in CheeseType) ,但这些似乎不起作用。

This type CheeseType = 'Cheddar' | 'Pepperjack' | 'Gouda'这种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. type CheeseType = 'Cheddar' | 'Pepperjack' | 'Gouda'在 JavaScript 中绝对没有表示,也没有以任何方式模拟。 You can figure it out by copy/pasting it in https://www.typescriptlang.org/play .您可以通过在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. type的唯一目的是防止您的代码在类型误用的情况下编译,因此您不必运行代码来发现明显的错误。

You can use enum which has a representation in JavaScript (an object) and will allow you to make runtime type checking.您可以使用在 JavaScript(一个对象)中具有表示形式的enum ,并允许您进行运行时类型检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM