TpeScript 中的字符串字面量类型是什么?
字符串字面量类型是在 TypeScript 1.8 版中添加的。字符串字面量量类型在实践中与联合类型和类型别名一起工作得很好。可以组合这些属性以提供类似字符串枚举的功能。字符串字面量量类型允许您为变量指定一组可能的字符串值,只有这些字符串值才能分配给变量。如果尝试将值分配给不是由字符串字面量类型定义的变量,TypeScript 会引发编译时错误。
示例 1:在此示例中,我们声明了一个变量,并将字符串字面量类型设置为 'a' 或 'b' 或 'c',为此使用了 pipe(|) 参数。当 'a' 分配给变量时,它不会给出错误,因为 'a'|'b'|'c' 指定变量可以是 'a' 或 'b' 或 'c'。当我们将 'd' 分配给变量 typescript 编译器会引发错误。
Javascript
let variable1: "a" | "b" | "c";
variable1 = "a";
console.log(variable1); // No error
variable1 = "d";
console.log(variable1); // Error
Javascript
let variable1: "a" | "b" | "c";
variable1 = "a";
console.log(variable1); // No error
variable1 = "A";
console.log(variable1); // Error
Javascript
type status = "in_review" | "publish_queue" | "published" | "awaiting_author";
let article_status: string;
function setArticleStatus(articleParams: status) {
article_status = articleParams;
console.log(article_status);
}
// No error status is set to 'in_review'
setArticleStatus("in_review");
Javascript
type status = "in_review" | "publish_queue" | "published" | "awaiting_author";
let article_status: string;
function setArticleStatus(articleParams: status) {
article_status = articleParams;
console.log(article_status);
}
// gives error status is set to 'delete'
setArticleStatus("delete");
输出:打字稿编译器输出:
error TS2322: Type '"d"' is not assignable to type '"a" | "b" | "c"'.
variable1 = "d";
~~~~~~~~~
执行javascript文件后的输出:
a
d
示例 2:字符串字面量量类型区分大小写,因此我们不能将大写值分配给需要小写的变量。在下面的示例中进行了演示。
Javascript
let variable1: "a" | "b" | "c";
variable1 = "a";
console.log(variable1); // No error
variable1 = "A";
console.log(variable1); // Error
输出:打字稿编译器输出:
two.ts:5:1 – error TS2820: Type ‘”A”‘ is not assignable to type ‘”a” | “b” | “c”‘. Did you mean ‘”a”‘? variable1 = “A”;
~~~~~~~~~
示例 3:此示例显示我们还可以使用函数为字符串字面量量类型的变量设置值。在这个例子中我们需要设置文章的状态,状态可以设置为“in_review”或者“publish_queue”或者“published”或者“awaiting_author”。当 'in_review' 传递给函数时,不会引发错误。当 'delete' 被传递给函数时,会引发错误,因为字符串不包含在状态中。
当 'in_review' 被传递给函数时。
Javascript
type status = "in_review" | "publish_queue" | "published" | "awaiting_author";
let article_status: string;
function setArticleStatus(articleParams: status) {
article_status = articleParams;
console.log(article_status);
}
// No error status is set to 'in_review'
setArticleStatus("in_review");
输出:
in_review
当“删除”传递给函数时。
Javascript
type status = "in_review" | "publish_queue" | "published" | "awaiting_author";
let article_status: string;
function setArticleStatus(articleParams: status) {
article_status = articleParams;
console.log(article_status);
}
// gives error status is set to 'delete'
setArticleStatus("delete");
输出:
error TS2345: Argument of type ‘”delete”‘ is not assignable to parameter of type ‘status’. setArticleStatus(“delete”);
~~~~~~~~
参考: https://www.typescriptlang.org/docs/handbook/literal-types.html#string-literal-types