多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
# 字符串字面值类型 > 原文: [https://howtodoinjava.com/typescript/string-literal-types/](https://howtodoinjava.com/typescript/string-literal-types/) 在 TypeScript 中,字符串字面值可让您指定`string`在其生命周期中必须具有的确切值。 您可以将其假定为“基于字符串的枚举”的形式,也称为`string`常量组。 ## 语法 在允许的不同`string`值之间使用“竖线”符号。 ```java type myVar = "value1" | "value2" | "value3" | "value4"; //upto N values //For example type AppStatus = "ACTIVE" | "INACTIVE" | "ONHOLD"; ``` ## 字符串字面值类型示例 让我们看看如何使用`string`字面值,以及如何无法使用。 1. #### 变量赋值 您只能将允许的值分配给字面值类型变量。 否则将是**编译时错误**。 ```java type AppStatus = "ACTIVE" | "INACTIVE" | "ONHOLD"; let currStatus: AppStatus; currStatus = "ACTIVE"; //OK currStatus = "DELETED"; //Error - Type '"DELETED"' is not //assignable to type 'AppStatus' ``` 2. #### 函数参数 您只能将允许的值传递给字面值类型参数。 否则将是**编译时错误**。 ```java type AppStatus = "ACTIVE" | "INACTIVE" | "ONHOLD"; function showMe(currentStatus: AppStatus): void { console.log(currentStatus); } showMe('ACTIVE'); //OK - Print 'ACTIVE' showMe('DELETED'); //Compile time Error ``` 将我的问题放在评论部分。 学习愉快!