In idiomatic Typescript, should I always declare a variable's type, or should I rely more on type inference?

旧时模样 提交于 2021-02-07 11:37:09

问题


At first, our team found ourselves writing lots of code like this because that's what we're used to in languages like ActionScript.

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

That's fine, but it can be simplified by relying more heavily on Typescript's 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 darn good at type inference. If I drop the type from the left-hand side of assignments, the compiler still knows what type that object is, and will still give a compile error if I try to do something on the variable the inferrred type can't do.

I like that it's less code to read, and less code to type. The example that declares types is beginning to feel "redundant" to me, but I'm worried that we might be setting ourselves up for trouble later. I'm curious what the community recommends, if anything.


回答1:


What I do for my project is not putting the type definition everywhere when it can be inferred because (as you already said) it is redundant.

What I'm currently not doing (but I really want to do it) is compiling with the --noImplicitAny any flag.

With that flag enabled you will get an error where it couldn't infer the type which is really helpful! You might want to look at that! See my example below.

The code below will give three errors when compiled with tsc --noImplicitAny tst.ts:

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

tst.ts(1,11): error TS7015: Array Literal implicitly has an 'any' type from widening.

tst.ts(2,5): error TS7005: Variable 'x' implicitly has an 'any' type.

tst.ts(5,11): error TS7017: Index signature of object type implicitly has an 'any' type.

This way when you doing something weird (accidentally) will give an error.



来源:https://stackoverflow.com/questions/24559636/in-idiomatic-typescript-should-i-always-declare-a-variables-type-or-should-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!