• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
class A {
}
class AChild extends A {
    public SpecialLog(): void {
        console.log("specialLog");
    }
}
class B {
}
        console.log("1 基本类型判断------string、number、object、null、undefined------->");
        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");       

结果:

断言的更多细节可以参考该文档


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
TypeScript-声明文件发布时间:2022-07-18
下一篇:
开始使用 TypeScript 和 React发布时间:2022-07-18
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap