class Color{
    color:string
    constructor(color:string){
        this.color = color
    }
}
class Shape {
    size:number
    constructor(size:number){
        this.size = size
    }
}
function getObj(type): Color | Shape {
    if (type == 0) {
        return new Color('red')
    }else{
        return new Shape(30);
    }
}
var obj1:Color | Shape = getObj(1);
console.log(obj1.size);  //此處會編譯異常,無法使用size
obj1 = getObj(0);
console.log(obj.color);  //此處會編譯異常,無法使用color
//基本資料類型使用typeof
function stringOrNumber(p:string | number){
    if(typeof p === 'string'){
        //此時編譯器將p推斷為string類型
        console.log(p.length);
    }else {
        //被推斷為number類型
        console.log(p / 2);
    }
}
//class類型使用instanceof
function colorOrShape(p:Color | Shape){
    if(p instanceof Color){
        //此時會推斷p為Color
        console.log(p.color);
    }else{
        //推斷為Shape
        console.log(p.size);
    }
}
//自訂類型推斷方法
function isColor(p: Color | Shape): p is Color {
    return p["color"] != undefined;
}
function isShape(p: Color | Shape): p is Shape {
    return p["size"] != undefined;
}
function colorOrShape2(p: Color | Shape) {
    if (isColor(p)){
        //此時會被推斷為color類型
        console.log(p.color);
    }
    if (isShape(p)){
        //推斷為shape類型
        console.log(p.size);
    }
}
今天的內容就先到這邊,明天開始將會介紹Vue。