一、类型缩小
从宽类型转换为窄类型的过程
常用于 处理联合类型变量的场景
// typeof 类型守卫
function printAll(str: string | string[] | null) {
if (typeof str === 'object') {
// “str”可能为 “null”
for (const s of str) {
console.log(s.toUpperCase())
}
} else if (typeof str === 'string') {
console.log(str.toUpperCase())
}
}
二、真值缩小
三、类型谓词
类型谓词 is:用来判断某个变量属于什么类型
二、函数
2.1 调用签名
// 函数签名
type DescribableFunction = {
description: string
(someArg: number): boolean
}
function doSomething(fn: DescribableFunction) {
console.log(fn.description + ' returned ' + fn(6))
}
// 函数签名可以用于函数类型别名,也可以用于接口
function myFunc(someArg: number): boolean {
return true
}
myFunc.description = 'This is my function'
doSomething(myFunc) // This is my function returned true
2.2 构造签名
class Ctor {
s: string
constructor(s: string) {
this.s = s
}
}
type someConstructor = {
(s: string): Ctor;
}