[TypeScript] Avoid any type

时间:2022-08-11 10:52:26

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());
}

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:

[TypeScript] Avoid any type

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());
}else{
console.log(parseFloat(num).toFixed());
}
}