[英]Inferring types in Typescript - : vs =
https://www.typescriptlang.org/docs/handbook/functions.html#inferring-the-types
推断类型 在使用示例时,您可能会注意到 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;
};
在这里写 : 而不是=
是什么意思:
let myAdd =
let myAdd2:
在 TypeScript 中, :
用于明确指示变量或参数的类型。
所以我们有:
let myAdd2
名为myAdd2
的变量
: (baseValue: number, increment: number) => number
其类型是 function ,它接受一个名为baseValue
的数字和另一个名为increment
的数字,并返回一个数字。
= function (x, y) {
return x + y;
};
这里的值是 function。
在myAdd
的情况下,函数的类型没有明确指定。 : (baseValue: number, increment: number) => number
部分被省略了。 所以它的类型是根据分配给它的值来推断的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.