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

时间:2020-02-25 18:54:30

标签: javascript typescript typescript-typings

假设我有一个type定义如下:type CheeseType = 'Cheddar' | 'Pepperjack' | 'Gouda'

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

我正在想象if (myString is CheeseType)if (myString in CheeseType)之类的东西,但是这些似乎不起作用。

1 个答案:

答案 0 :(得分:1)

class Item { public: virtual double GetTotalPrice(); }; //Class artifact now inherits Item class Artifact : public Item { private: string GUID; string Name; string Description; string Category; double Price; double Discount; enum DiscountType { Amount, Percentage }; int Quantity; public: //Constructor Artifact(string GUID, string Name, string Description, string Category, double Price, double Discount, int Quantity) { this->GUID = GUID; this->Name = Name; this->Description = Description; this->Category = Category; this->Price = Price; this->Discount = Discount; this->Quantity = Quantity; } //default constructor Artifact(); void set_name(const string& name) { Name = name; } void set_price(double price) { if (Price > 0) { Price = price; } else cout << "Price cannot be negative!"; }; int main() { vector<Artifact> art; art.emplace_back("Ipad", 349.99); art.emplace_back("Gameboy", 29.99); art.emplace_back("Xbox", 229.99); art.emplace_back("SamsungTV", 559.99); art.emplace_back("AirCon", 319.99); return 0; } 绝对没有JavaScript表示,也没有以任何方式进行仿真。您可以通过将其复制/粘贴到https://www.typescriptlang.org/play中来找出答案。

因此,您将无法在运行时检查类型。 type CheeseType = 'Cheddar' | 'Pepperjack' | 'Gouda'的唯一目的是防止在类型滥用的情况下编译您的代码,因此您不必运行代码即可注意到明显的错误。

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