其他分享
首页 > 其他分享> > 类型缩小

类型缩小

作者:互联网

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)

标签:function,console,log,value,缩小,Student,类型,type
来源: https://www.cnblogs.com/xiaoqi11/p/15751927.html