首页 > 其他 > 详细

[TypeScript] Avoid any type

时间:2016-03-20 07:04:23      阅读:195      评论:0      收藏:0      [点我收藏+]

To avoid using "any" type is a best pratice. The reason for that is it disable the power of typescirpt to helping check you during the compile time. For example:

    currency(num: number){
        cosnole.log(num.toFixed(2));
    }

In our currency function, it should accept a number not a string, because toFixed is a method for number type. 

 

In typescript, it will tell you, if the type is not number, but string, it will report error:

技术分享

 

If you cannot sure it is a string or number type, you can use unit type:

    currency(num: string|number){
        if(typeof num === "number"){
            cosnole.log(num.toFixed(2));
        }else{
            console.log(parseFloat(num).toFixed(2));
        }
    }

 

[TypeScript] Avoid any type

原文:http://www.cnblogs.com/Answer1215/p/5297079.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!