TypeScript - 字符串字面量类型

字符串字面量类型用来约束取值只能是某几个字符串中的一个

type EventNames = 'click' | 'scroll' | 'mousemove';
function handleEvent(ele: Element, event: EventNames) {
  // do something
}
 
handleEvent(document.getElementById('hello'), 'scroll'); // 没问题
handleEvent(document.getElementById('world'), 'dbclick'); // 报错,event 不能为 'dbclick'
 
// index.ts(7,47): error TS2345: Argument of type '"dbclick"' is not assignable to parameter of type 'EventNames'.

上例中,我们使用 type 定了一个字符串字面量类型 EventNames,它只能取三种字符串中的一种。注意,类型别名与字符串字面量类型都是使用 type 进行定义。

转载于:https://www.cnblogs.com/xjy20170907/p/10882758.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,让我来回答你的问题。 1. TypeScript类型保护与区分类型 类型保护是 TypeScript 中用来区分不同类型的机制,可以通过 typeof、instanceof、in 等运算符来实现。例如: ```typescript function printLength(strOrArr: string | any[]) { if (typeof strOrArr === 'string') { console.log(strOrArr.length); // string类型 } else { console.log(strOrArr.length); // 数组类型 } } ``` 2. TypeScript 的联合类型 联合类型是指变量可以是多种不同类型之一,可以使用“|”符号将多个类型组合起来。例如: ```typescript let numOrStr: number | string = 5; numOrStr = "hello"; ``` 3. TypeScript 的交叉类型 交叉类型是指将多个类型合并成一个类型,可以使用“&”符号将多个类型组合起来。例如: ```typescript interface A { a: number; } interface B { b: string; } type C = A & B; const c: C = { a: 1, b: "hello" }; ``` 4. TypeScript类型别名 类型别名是为一个类型定义一个别名,可以使用“type”关键字来定义。例如: ```typescript type MyString = string; const str: MyString = "hello"; ``` 5. TypeScript 的接口 vs. 类型别名 接口和类型别名都可以用来定义类型,但有一些不同之处。接口可以被类实现,也可以被扩展,而类型别名只能定义别名。例如: ```typescript interface Person { name: string; age: number; } type PersonAlias = { name: string; age: number; }; class Student implements Person { name: string; age: number; grade: number; constructor(name: string, age: number, grade: number) { this.name = name; this.age = age; this.grade = grade; } } type StudentAlias = PersonAlias & { grade: number; }; const student: StudentAlias = { name: "Tom", age: 18, grade: 3 }; ``` 6. TypeScript字符串字面量类型 字符串字面量类型是指将字符串字面量作为类型,可以使用“|”符号将多个字符串字面量组合起来。例如: ```typescript type Gender = "male" | "female"; interface Person { name: string; age: number; gender: Gender; } const person: Person = { name: "Tom", age: 18, gender: "male" }; ``` 希望这些解释能够对你有所帮助。如果你还有其他问题,可以继续提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值