我是靠谱客的博主 冷酷薯片,这篇文章主要介绍Typescript学习 类型守卫,现在分享给大家,希望可以做个参考。

in 关键字

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
interface Admin { name: string privileges: string[] } interface Employee { name: string startDate: Date } type UnKnownEmployee = Employee | Admin function printEmployeeInformation(emp: UnKnownEmployee) { console.log("Name: " + emp.name) if ("privileges" in emp) { console.log("Privileges:" + emp.privileges.join("、")) } if ("startDate" in emp) { console.log("Start Date:" + emp.startDate) } } const params: Admin = { name: "amin", privileges: ["张龙"] } const params2: Employee = { name: "amin", startDate: new Date() } printEmployeeInformation(params) printEmployeeInformation(params2)

typeof

typeof v === "typename" // string number boolean symbol

复制代码
1
2
3
4
5
6
7
8
9
10
11
function testTypeof(value: string, type: string | number) { if (["number", "string"].includes(typeof type)) { console.log(typeof type) if (typeof type === "number") { return new Array(type + 1).join("-") + value } return type + value } console.log("err") }

instanceof

console.log(padder instanceof SpaceRepeatingPadder) // true false

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
interface Padder { getPaddingString(): string } class SpaceRepeatingPadder implements Padder { constructor(private numSpaces: number) {} getPaddingString(): string { return Array(this.numSpaces + 1).join("-") } } class StringPadder implements Padder{ constructor(private value: string) {} getPaddingString(): string { return this.value } } let padder: Padder = new SpaceRepeatingPadder(6) let padder2: Padder = new StringPadder("amin") if (padder instanceof SpaceRepeatingPadder) { console.log(padder.getPaddingString()) } if (padder2 instanceof StringPadder) { console.log(padder2.getPaddingString()) }

自定义类型保护的类型谓词

复制代码
1
2
3
4
5
6
7
8
9
10
11
function isNumber(x: any): x is number { return typeof x === "number" } function isString(x: any): x is string { return typeof x === "string" } console.log(isNumber("amin")) // false console.log(isNumber(5)) // true console.log(isString(5)) // false console.log(isString("amin")) // true

最后

以上就是冷酷薯片最近收集整理的关于Typescript学习 类型守卫的全部内容,更多相关Typescript学习内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(124)

评论列表共有 0 条评论

立即
投稿
返回
顶部