TypeScript类型判断typeof,instanceof,以及as断言

class A {
}
class AChild extends A {
    public SpecialLog(): void {
        console.log("specialLog");
    }
}
class B {
}
        var str: string = "hello";
        var b1: number;
        var b2: number = 3;
        var c1: any;
        var c2: any = 6;
        var c3: any = "6";
        var d1: Array<number>;
        var d2: Array<number> = [1, 2, 34];
        var e = null;
        console.log(typeof str === 'string')
        console.log(typeof str === 'number')
        console.log(typeof b1)
        console.log(typeof b2)
        console.log(typeof c1)
        console.log(typeof c2)
        console.log(typeof c3)
        console.log(typeof d1)
        console.log(typeof d2)
        console.log(typeof e)



        console.log("2  引用类型判断-------接口或类类型,Array和RegExp------->")
        let a: A = new A();
        let aChild: AChild = new AChild();
        a = aChild;
        console.log(a instanceof A);
        console.log(aChild instanceof A);
        console.log(a instanceof B);

        if (a instanceof AChild) { //instanceof的类型转换功能
            a.SpecialLog();
        }
        console.log([] instanceof Array);
        console.log({} instanceof Object);
        console.log(/\d/ instanceof RegExp);


        console.log("3 断言-----------即as和<>的用法------>")
        let p1: number = 2345;
        let p2: any = 643;
        let p3: any = "643";
        // console.log("p1.length:"+p1.length+",p2.length:"+p2.length);//编译器直接报错
        // console.log("p1.length:" + (p1 as String).length + ",p2.length:" + (p2 as String).length);//因为p1确定是number类型,这里强转报错
        console.log("p2.length:" + p2.length);
        console.log("p2.length:" + (p2 as String).length);
        console.log("p3.length:" + p3.length);
        console.log("p3.length:" + (p3 as String).length);
        console.log("1:" + (a as B));
        console.log("2:" + (a as AChild));
        console.log("3:" + (a as AChild).SpecialLog());
        console.log("4:" + (<AChild>a).SpecialLog());
        console.log("-------->end");       

结果:


运行结果

推荐阅读更多精彩内容