Typescript学习笔记-类型保护与类型区分

主要用于在编写代码的时候,少用类型断言,更好的可读性。贴代码

//person is Teacher 主谓宾语句进行类型保护,主要用于在编写代码的时候,少用类型断言,更好的可读性。
interface Teacher {
    teach(): void;
}
interface Student {
    learn(): void;
}
interface Docter {
    nice(): void;
}
function getPerson(): Teacher | Student | Docter{
    return {
        teach: () => { }
    } as Teacher;
}

function isTeacher(person: Teacher | Student | Docter): person is Teacher {
    return (<Teacher>person).teach !== undefined
}
function isStudent(person: Teacher | Student | Docter): person is Student {
    return (<Student>person).learn !== undefined
}
const person = getPerson();
if (isTeacher(person)) {
    person.teach();
} else if (isStudent(person)) {
    person.learn();
} else {
    person.nice();
}

猜你喜欢

转载自www.cnblogs.com/bookingmo/p/12313020.html