In idiomatic Typescript, should I always declare the type of the variable, or should I rely more on type inference?

At first, our team found many such codes, because that is what we are used to in languages ​​like ActionScript.

var arrayOfFoo : Array<Foo> = new Array<Foo>();
//Then, sometime later:
var someFoo : Foo = arrayOfFoo[0];
someFoo.someFooMethod();

This is great, but it can be simplified by relying more heavily on Typescript type inference:

//No need to declare the type ": Array<Foo>" here:
var arrayOfFoo = new Array<Foo>();

//Again, no need to declare that someFoo is a Foo
var someFoo = arrayOfFoo[0];
someFoo.someFooMethod();

Typescript is pretty good at type inference. If I omit the type on the left side of the assignments, the compiler still knows what type this object is, and still give a compilation error if I try to do something with a variable that type inferrred cannot do.

, . , , "" , , , , . , , .

+4
1

, , , , ( ) .

, ( ), -noImplicitAny .

, , ! ! . .

tsc --noImplicitAny tst.ts:

var arr = [];
var x = null;
var a: string[] = [];
var s = a["foo"]

tst.ts(1,11): TS7015: Literal "any" .

tst.ts(2,5): TS7005: "x" "any" .

tst.ts(5,11): TS7017: "any" .

, - (), .

+5

Source: https://habr.com/ru/post/1547047/


All Articles