简体   繁体   English

打字稿中的“任何”

[英]“any” in Typescript

I am beginner in typescript.我是打字稿的初学者。 I have a doubt in usage of "any" type.我对“any”类型的使用有疑问。

Using "any" is basically opting out type checking if I am right.如果我是对的,使用“any”基本上是选择退出类型检查。 For example例如

  1. var num:any = 12

  2. var num = 12

we could probably use the second one itself, what's the need for 'any'?我们可能可以使用第二个本身,“任何”有什么需要?

While the two are equivalent in use (because any is the default type when unspecified) by explicitly specifying the type as any , you explicitly declare the intent.虽然两者在使用中是等效的(因为any在未指定时是默认类型),但通过将类型显式指定为any ,您可以显式声明意图。

Intellisense, where available, will display the type as any , allowing easier understanding how your variable is meant to be used. Intellisense(如果可用)会将类型显示为any ,以便更轻松地了解您的变量的用途。

First of all - If we speak about Typescript, lets avoid the var key-word.首先 - 如果我们谈论 Typescript,让我们避免使用 var 关键字。

We may need to describe the type of variables that we do not know when we are writing an application.我们在编写应用程序时可能需要描述我们不知道的变量类型。 These values may come from dynamic content, eg from the user or a 3rd party library.这些值可能来自动态内容,例如来自用户或第 3 方库。 In these cases, we want to opt-out of type-checking and let the values pass through compile-time checks.在这些情况下,我们希望选择退出类型检查并让值通过编译时检查。 To do so, we label these with the any type:为此,我们将这些标记为 any 类型:

Example to this:例如:

let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean

More: Types in Typescript更多: Typescript 中的类型

Any: any type.任何:任何类型。 Used when impossible to know the type.在不可能知道类型时使用。 When you declare type as any, you can reassign any type of value in that variable.当您将 type 声明为 any 时,您可以在该变量中重新分配任何类型的值。

var num:any = 12;
num = boolean;
num = "abcd"

any opts out type checking as you have said.正如您所说, any选择退出类型检查。 The second description you have came up with (without any ) will compile too.您提出的第二个描述(没有any )也将编译。 But it is not valid(*) when you use linting like tslint .但是当你使用像tslint这样的linting时它是无效的(*)。

(*) By not valid , I meant the IDE you use will pop up an alert. (*) not valid是指您使用的 IDE 会弹出警报。 But, to the bottom line;但是,归根结底; any valid Javascript code is also valid for Typescript on the grounds of compiling. 任何有效的 Javascript 代码也以编译为由对 Typescript 有效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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