TypeScript--类型保护

联合类型表示一个值可以是几种类型之一。 我们用竖线(|)分隔每个类型,所以 number | string | boolean 表示一个值可以是 numberstring,或 boolean

示例

function doSomething(args: string | number) {
    if (typeof args === 'string') {
        console.log(args.length)
    } else {
        console.log(args.toFixed(2))
    }
}

// ✅正确
// 
doSomething('hello')

// ✅正确
doSomething(100)

// ❌错误
// Argument of type 'boolean' is not assignable to parameter of type 'string | number'.
doSomething(true)

TypeScript 不确定一个联合类型的变量到底是哪个类型的时候,我们只能访问此联合类型中共有的属性或方法

interface Dog {
    name: string
    bark: () => void
}

interface Bird {
    name: string
    fly: () => void
}

// ✅访问共有的 'name' 属性
function namePets(args: Dog | Bird) {
    console.log('hello ' + args.name)
}

当我们确实需要在还不确定类型的时候就访问其中一个类型特有的属性或方法时,这时就需要用到类型保护。

in

in 操作符对 对象 上的属性是否存在进行安全检查

interface Dog {
    name: string
    bark: () => void
}

interface Bird {
    name: string
    fly: () => void
}

function doSomething(args: Dog | Bird) {
    if ('bark' in args) {
        args.bark()
    } else {
        args.fly()
    }
}

typeof

typeof 也能确定类型,不过只能用于 js 的基本数据类型(null 除外),而不能用于 interfacetype 定义的类型,因为在运行时这些类型就不在了。

说明:

  • typeof null => object
function doSomething(args: string | number) {
    if (typeof args === 'string') {
        console.log('args is string')
    } else {
        console.log('args is number')
    }
}

instanceof

instanceof 用于校验类,和 interfacetype 不同的是,类的类型信息会在运行时保留,所以可以用 instanceof 作校验

class Person {
    constructor(public name: string, public age: number) {}
}

function infoPerson(obj: any) {
    if (obj instanceof Person) {
        console.log(`${obj.name} is ${obj.age} years old`)
    }
}

自定义类型保护

interface Dog {
    name: string
    bark: () => void
}

interface Bird {
    name: string
    fly: () => void
}

function isDog(args: Dog | Bird): args is Dog {
    return 'bark' in args
}

function doSomething(args: Dog | Bird) {
    if (isDog(args)) {
        args.bark()
    } else {
        args.fly()
    }
}

=== / !==

type CheckState = 'yes' | 'no' | 'unknown'

function doSomething(args: CheckState) {
    if (args === 'yes') {
        console.log('check state is yes')
    } else if (args === 'no') {
        console.log('check state is no')
    } else {
        console.log('unknown check state')
    }
}
posted @ 2021-04-13 09:45  蓦然回首!  阅读(111)  评论(0编辑  收藏  举报