类型推断的可靠性如何?

以撒

我才刚刚起身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,始终会自动推断类型。您可能偶尔需要注释比推断的类型更具体的类型,但是至少推断的类型将始终是特定的,而不是anyconst应该优先于let任何可能的方式)

如果确实需要使用let(有时需要使用),则可以在初始化时为其分配一个值(并且类型推断将起作用),或者使用类似类型的注释

let number1: number;

以便正确键入,否则将会any并会导致问题。

在变量最初没有分配任何内容时使用类型注释非常好。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章