简体   繁体   中英

Typescript: using let (best practice)

I'm using TypeScript and I'm new using it so I have a question about declaring variables.

When we declare a variable we use let name: type = value . Ok, I always assign the type of the variable: if I want a String I declare as string , the same with booleans and numbers. I saw the type any which make the variable of any type.

The question is: if I declare a variable as a number, is necessary to use let myNumber: number = 23; ? is necessary to say that the type is a number?

If I don't do, and do a typeOf(myNumber) it returns number, but for TypeScript is number or is any ?

And is best practice to always set the type when assign a value to the variable or it isn't important?

Typescript will avoid making variables of type any . When you set the option noImplicityAny to true in your tsconfig.json , it will even give you an error when you don't specify a type and Typescript can only set the type to any .

Generally speaking, when you specify a type in your let as in your example...

let myNumber: number = 23;

... you set the type explicitly . That means you clearly communicate your intent to make this variable a number . When you assign a non-numeric value, you will get an error. There is nothing wrong with declaring all your variables with an explicit type, since that only improves the clarity of your code.

The other option is to type your variable implicitly . That can only be done when you assign a value to your variable upon declaration:

let myNumber = 23;

Since you assign a numeric literal to your variable, Typescript can infer the type of the variable and will consider it a number. In some cases it is useful to override inferrence, for example for union types:

let myNumberOrText: number | string = 23;

When you have noImplicitAny set to true , implicit typings to any are forbidden. So...

let myAny = { FirstName: "John", LastName: "Doe" };

...will cause an error, because it would implicitly type to any . The explicit version is still allowed. So you can write...

let myAny: any = { FirstName: "John", LastName: "Doe" };

...although in Typescript you preferably declare a class or interface and use it for typing (assuming you have declared a type Person ):

let myPerson: Person = { FirstName: "John", LastName: "Doe" };

The whole point of Typescript is to introduce static typing to JavaScript. If you declare your variables with type any , you will have no advantage from static typing and you can just use plain JavaScript.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM