仅允许具有 TypeScript 类型的特定字符串值
使用字符串文字类型仅允许使用 TypeScript 类型的特定字符串值,例如 const str: 'draft' | 'sent' = 'draft';
. 字符串文字允许我们引用类型位置中的特定字符串。 如果指定的字符串不是文字类型,则会抛出错误。
// ✅ with interface
interface Person {
name: 'Alice' | 'Bob' | 'Carl';
}
const p: Person = {
name: 'Alice',
};
// ✅ with Type Alias
type Sizes = 'small' | 'medium' | 'large';
const s: Sizes = 'small';
// ✅ inline
const str: 'draft' | 'sent' = 'draft';
// ✅ for function parameters
function logMessage(message: 'hello world' | 'howdy world') {
console.log(message);
}
logMessage('hello world');
这些示例展示了如何使用字符串文字类型来仅允许分配给特定的字符串值。
字符串文字类型允许我们引用类型位置中的特定字符串。
分配不是文字类型成员的字符串会导致错误。
// ⛔️ Type '"hello"' is not assignable to
// type '"draft" | "sent"'.ts(2322)
const str: 'draft' | 'sent' = 'hello';
考虑字符串文字类型的一种简单方法是 – 它们是具有特定字符串值而不是类型的联合类型。
文字类型也可用于数字和布尔值。 例如,类型
boolean
只是联合类型true | false
的别名。
或者,我们可以使用枚举。
使用枚举仅允许使用 TypeScript 类型的特定字符串值,例如 const emailStatus: EmailStatus = EmailStatus.Read;
。 枚举允许我们定义一组命名常量。 如果指定的字符串不是枚举的成员,则会抛出错误。
enum EmailStatus {
Read = 'READ',
Unread = 'UNREAD',
Draft = 'DRAFT',
}
// ✅ using interfaces
interface JobEmails {
status: EmailStatus;
}
const obj: JobEmails = {
status: EmailStatus.Read,
};
// ✅ inline assignment
const emailStatus: EmailStatus = EmailStatus.Read;
枚举有时比字符串文字类型更容易阅读。
请注意
,枚举是真实对象,存在于运行时。 我们可以使用点符号来访问枚举的属性。
示例中的 emailStatus
变量只能具有 EmailStatus 枚举中存在的 3 个值之一。
分配不同的字符串会导致类型检查器抛出错误。
enum EmailStatus {
Read = 'READ',
Unread = 'UNREAD',
Draft = 'DRAFT',
}
// ⛔️ Error: Type '"hello"' is not
// assignable to type 'EmailStatus'.ts(2322)
const emailStatus: EmailStatus = 'hello';
使用枚举优于字符串文字类型的主要优点是 – 它们使我们的代码更易于阅读和组织。
枚举的全部目的是定义一组命名和相关的常量。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。