在惯用的Typescript中,我应该始终声明变量的类型,还是应该更多地依赖于类型推断? [英] In idiomatic Typescript, should I always declare a variable's type, or should I rely more on type inference?

查看:95
本文介绍了在惯用的Typescript中,我应该始终声明变量的类型,还是应该更多地依赖于类型推断?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

起初,我们的团队发现自己编写了许多这样的代码,因为这是我们在ActionScript之类的语言中所习惯的.

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

很好,但是可以通过更加依赖Typescript的类型推断来简化它:

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非常擅长类型推断.如果我从赋值的左侧删除类型,则编译器仍会知道该对象是什么类型,并且如果我尝试对推断的类型无法执行的变量进行操作,仍会产生编译错误.

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.

推荐答案

我为我的项目所做的工作并不是在可以推断类型定义的情况下就把它放在任何地方,因为(正如您已经说过的那样)它是多余的.

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.

我目前不做的(但我真的很想做)是使用--noImplicitAny any标志进行编译.

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.

使用tsc --noImplicitAny tst.ts编译时,下面的代码将给出三个错误:

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):错误TS7015:数组文字在扩展时隐式具有"any"类型.

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

tst.ts(2,5):错误TS7005:变量"x"隐式具有"any"类型.

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

tst.ts(5,11):错误TS7017:对象类型的索引签名隐式具有"any"类型.

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.

这篇关于在惯用的Typescript中,我应该始终声明变量的类型,还是应该更多地依赖于类型推断?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆