WIP: Typescript 笔记

本篇记录 ts 类型的学习笔记

参考资料

intersection type (交集类型)

TODO

Union Type (联合类型)

Union Type 和 intersection type 很类似,但是还有很多的不同。例如:

/** * Takes a string and adds "padding" to the left. * If 'padding' is a string, then 'padding' is appended to the left side. * If 'padding' is a number, then that number of spaces is added to the left side. */ function padLeft(value: string, padding: any) { if (typeof padding === "number") { return Array(padding + 1).join(" ") + value; } if (typeof padding === "string") { return padding + value; } throw new Error(`Expected string or number, got '${padding}'.`); } padLeft("Hello world", 4); // returns " Hello world"

上述代码的意图是给指定的字符串左补齐内容,可以是数字或者字符串。使用 any 类型,使得参数限制形同虚设,还要再判断类型再使用。

需求不变,使用 union type 改写一下,例如:

function padLeft(value: string, padding: number | string) { // ... }

Type Guards

根据 TypeScript 官方定义:

A type guard is some expression that performs a runtime check that guarantees the type in some scope.

Type Guard 是一个在运行时执行的检查,来保证类型在期望的范围内。

© 2015-2023, Bill X.