[TypeScript] Avoid any type

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)