繁体   English   中英

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

[英]Typescript: Determining whether a string is in a string union type

假设我有一个这样定义的typetype CheeseType = 'Cheddar' | 'Pepperjack' | 'Gouda' type CheeseType = 'Cheddar' | 'Pepperjack' | 'Gouda' type CheeseType = 'Cheddar' | 'Pepperjack' | 'Gouda'

给定一个string ,如何确定该string值是否在CheeseType列表中?

我想像if (myString is CheeseType)if (myString in CheeseType) ,但这些似乎不起作用。

这种type CheeseType = 'Cheddar' | 'Pepperjack' | 'Gouda' type CheeseType = 'Cheddar' | 'Pepperjack' | 'Gouda' type CheeseType = 'Cheddar' | 'Pepperjack' | 'Gouda'在 JavaScript 中绝对没有表示,也没有以任何方式模拟。 您可以通过在https://www.typescriptlang.org/play 中复制/粘贴来弄清楚。

因此,您将无法在运行时检查类型。 type的唯一目的是防止您的代码在类型误用的情况下编译,因此您不必运行代码来发现明显的错误。

您可以使用在 JavaScript(一个对象)中具有表示形式的enum ,并允许您进行运行时类型检查。

暂无
暂无

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

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