简体   繁体   English

TypeScript 不一致 - 为什么编译器允许 object 属性值赋值但不允许方法返回值赋值?

[英]TypeScript inconsistency - why does compiler allow object property value assignment but no method return value assignment?

I am developing an Angular project using jQuery and noticed a strange anomaly.我正在使用 jQuery 开发一个 Angular 项目并注意到一个奇怪的异常。 Look at the below TypeScript code from an Angular component class:从 Angular 组件 class 中查看以下 TypeScript 代码:

let foo :any | undefined = window.innerWidth * 0.26; // first line has no error
let bar :any | undefined = $(window).width() * 0.26; // second line has an error

The second line returns a compiler error: Object is possibly 'undefined'.ts(2532) .第二行返回编译器错误: Object is possibly 'undefined'.ts(2532) Let us assume that there is such a case and the compiler is right, when the window object was somehow not initialized and look at this code;让我们假设存在这种情况并且编译器是正确的,当window object 不知何故未初始化时,请查看这段代码;

let asd :number = window.innerWidth * 0.26; // third line also has no error

In this case, there can be two errors (see this link for reference);在这种情况下,可能会出现两个错误(请参阅此链接以供参考);

  1. window object has no innerWidth property defined, so asd will receive undefined as value, which is not of number type, so the compiler should throw Type 'undefined' is not assignable to type 'number'.ts(2322) error or the Object is possibly 'undefined'.ts(2532) error window object 没有定义innerWidth属性,所以asd将接收undefined作为值,它不是number类型,所以编译器应该抛出Type 'undefined' is not assignable to type 'number'.ts(2322)错误或者Object is possibly 'undefined'.ts(2532)错误
  2. window object was not instantiated, in which case it's type is null , so asd will receive no value and the program will return with ReferenceError . window object 没有被实例化,在这种情况下它的类型是null ,所以asd将不会收到任何值,程序将返回ReferenceError

For proof of concept, see this snapshot from w3schools' TryIt editor;有关概念证明,请参阅w3schools 的 TryIt编辑器的快照;

概念验证

So, my question is: why does the TypeScript compiler show error for the value assignment with jQuery method (first line), but no compiler error using the native JS object property approach (second and third line)?所以,我的问题是:为什么 TypeScript 编译器使用 jQuery 方法(第一行)显示赋值错误,但使用本机 JS object 属性方法(第二行和第三行)没有编译器错误?

The return type of的返回类型

$(window).width()

is

number | undefined

The multiplication乘法

$(window).width() * 0.26

is only allowed for two numbers.只允许两个数字。 You have to handle the case for undefined .您必须处理undefined的情况。 I would use a temporary variable and the conditional ternary operator:我会使用一个临时变量和条件三元运算符:

const width = $(window).width();
let bar :any | undefined = width ? width * 0.26 : undefined;

The other lines don't cause an error because其他行不会导致错误,因为

window.innerWidth

has type有类型

number

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

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