我才刚刚起身typescript
并遇到type inference
。
现在,根据指导者讲,用来初始化变量而type
不是依靠它并不是最佳实践,type inference
但立即出现以下错误
function add(n1: number, n2: number, showResult: boolean, phrase: string) {
const result = n1 + n2;
if (showResult) {
console.log(phrase + result);
}
return result;
}
let number1;
number1 = '5';
const number2 = 2.8;
add(number1, number2, printResult, resultPhrase);
从上面的代码片段中可以明显看出,它可以进行string
类型检查,因此,如果我们不依赖type inference
而是显式设置类型,这会是一个更好的主意吗?如下面
let number1: number;
number1 = '5';
并立即从上述代码中得到错误。下图是不信任的证明type inference
。
number1
is typed as any
, because nothing is assigned to it when it's declared. And any
is, unfortunately, assignable to anything - this is why using it is strongly discouraged. With
function add(n1: number,
if you call add
where the first argument passed is of type any
, it'll compile.
Assigning another value to the variable after the variable has been declared doesn't change the type - Typescript still sees it typed as any
.
To keep from making these sorts of mistakes, make sure to enable noImplicitAny
in your tsconfig - it will throw errors when you attempt to use an any
where a more specific type is expected.
其他有用的方法是const
代替let
-与一起使用const
,始终会自动推断类型。您可能偶尔需要注释比推断的类型更具体的类型,但是至少推断的类型将始终是特定的,而不是any
。(const
应该优先于let
任何可能的方式)
如果确实需要使用let
(有时需要使用),则可以在初始化时为其分配一个值(并且类型推断将起作用),或者使用类似类型的注释
let number1: number;
以便正确键入,否则将会any
并会导致问题。
在变量最初没有分配任何内容时使用类型注释非常好。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句