简体   繁体   English

Typescript 中的推断类型 -: vs =

[英]Inferring types in Typescript - : vs =

https://www.typescriptlang.org/docs/handbook/functions.html#inferring-the-types https://www.typescriptlang.org/docs/handbook/functions.html#inferring-the-types

Inferring the types In playing with the example, you may notice that the TypeScript compiler can figure out the type even if you only have types on one side of the equation:推断类型 在使用示例时,您可能会注意到 TypeScript 编译器可以计算出类型,即使您在等式的一侧只有类型:

// The parameters 'x' and 'y' have the type number
let myAdd = function (x: number, y: number): number {
  return x + y;
};

// myAdd has the full function type
let myAdd2 : (baseValue: number, increment: number) => number = function (x, y) {
  return x + y;
};

What does it mean when : is written instead of = here:在这里写 : 而不是=是什么意思:

let myAdd =
let myAdd2:

In TypeScript, : is used to explicitly indicate the type of a variable or parameter.在 TypeScript 中, :用于明确指示变量或参数的类型。

So we have:所以我们有:

let myAdd2

A variable named myAdd2名为myAdd2的变量

 : (baseValue: number, increment: number) => number 

Whose type is a function that takes a number called baseValue and another number called increment , and returns a number.其类型是 function ,它接受一个名为baseValue的数字和另一个名为increment的数字,并返回一个数字。

= function (x, y) {
  return x + y;
};

and whose value is this function here.这里的值是 function。

In the case of myAdd , the function's type is not explicitly specified.myAdd的情况下,函数的类型没有明确指定。 The : (baseValue: number, increment: number) => number part is left out. : (baseValue: number, increment: number) => number部分被省略了。 So its type inferred based on the value being assigned to it.所以它的类型是根据分配给它的值来推断的。

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

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