类型缩小

1、typeof的类型缩小

type idType = number | string
function printId(id: idType) {
    if (typeof id === 'string') {
        console.log('字符串类型');
    } else {
        console.log('数字类型');
    }
}
printId('123')

2、平等类型缩小(=== == !==)

type derectionType = 'left' | 'right' | 'bottom' | 'top';
function print(value: derectionType) {
    if (value === 'left') {
        console.log('是left类型');
    }
}
print('left')

3、instanceof 判断对象是不是构造函数的实例或者构造函数子类的实例

function printTime(value: string | Date) {
    if (value instanceof Date) {
        console.log('是');

    }
}

//对象实例
class Student {
    studing() {
        console.log(`我是学生对象,我在学习`);
    }
}

class Teacher {
    teaching() {
        console.log(`我是老师对象,我正在教学生`);
    }
}

function work(p: Student | Teacher) {
    if (p instanceof Student) {
        p.studing()
    } else {
        p.teaching()
    }
}

//因为是class类,所以要new创建一个实例
const s = new Student;
work(s);

4、in

//使用type定义类型
type Fish = {
    swimming: () => void
}

type Dog = {
    shoutting: () => void
}

function kk(value: Fish | Dog) {
    if ('swimming' in value) {
        value.swimming()
    } else {
        value.shoutting()
    }

}

//创建指定类型的变量
const fish: Fish = {
    swimming() {
        console.log(`我是鱼,我在游泳`);

    }
}
const dog: Dog = {
    shoutting() {
        console.log(`我是一只小狗,我在叫`);

    }
}
//把变量当成参数传进去
kk(dog)
posted @ 2021-12-31 10:30  最爱宋人头  阅读(46)  评论(0编辑  收藏  举报