首页 > 解决方案 > 为什么 Typescript 编译器不推断实例变量的范围?

问题描述

编辑

这不是重复的。链接的问题是询问为什么ES6规范没有隐式定义“this”。这不是这里要问的。

这里的问题是为什么 Typescript 编译器不针对这一事实进行调整,更具体地说,是技术性质的原因吗?

结束编辑

忽略设计师偏好等原因,是否存在阻止 Typescript 编译器自动映射local_variablethis.local_variable以下示例中的技术问题?

import { Component, Input, OnInit } from '@angular/core';
@Component({
  selector: 'app-example',
  templateUrl: './app-example.component.html',
  styleUrls: ['./app-example.component.css']
})
export class ExampleComponent implements OnInit {
  @Input() local_variable: any;

  constructor() { }

  ngOnInit() {
    if (local_variable) {
      console.log(local_variable);
    }
  }

}

在像 C++ 或 Java 这样的语言中,人们会期望编译器推断 的范围local_variable,但在 Typescript 中,编译器会抛出错误 TS2663,并抱怨它Cannot find name 'local_variable'. Did you mean the instance member 'this.local_variable'?

为什么?为什么我们会被看似多余的“这个”所困?

----

由于我现在无法添加另一个答案,因此我将把名为 @webstrand 的个人的回复留给问题正文中 Typescript gitter 中提出的相同查询。

webstrand @webstrand 15:29
Typescript, once you remove the type annotations, must be completely compatible with regular javascript. This is one of the project's major guidelines.
There are a few exceptions, such as enum and namespace. But they're dead simple to transpile.
So, since the underlying javascript doesn't infer this, Typescript can't either.
@l4cr0ss Historically, the reason why javascript require the seemingly redundant this is because of an old mis-feature: with.

Jefferson Hudson @l4cr0ss 15:36
Ok. I understand that, thanks. Now, you say there are a few exceptions which are allowed because they are simple to transpile. Is it the case that such resolution could be implemented as part of the transpilation process, but because of its complexity the choice is made not to? Or, would it really break something?

webstrand @webstrand 15:42
@l4cr0ss One of the features of typescript, used by some really large projects, is that it can "transpile" directly to javascript without resolving and checking all of the types. So the compiler must be able to compile to javascript without any type information at all. To correctly infer this in all cases would require that the compiler always have type information available.

webstrand @webstrand 15:43
This is a really reassuring feature to have in an ecosystem like Javascript where there's so much churn in projects. IF typescript dies in a year, I can run all of my code through the transpile process and get back pure javascript
In fact, typescript has a type-checking mode where all the type information is stored as jsdoc-style comments.
Obviously, in that case, you can't use enum or namespace either.
As a side note , use of namespace is usually frowned upon. It comes from an era before ES supported modules natively.

标签: typescript

解决方案


编译器错误信息很清楚,不是吗?编译器确实推断出您可能的意思是this.local_variable. 至少在没有该名称的全局变量的情况下,正如 wvteijlingen 的回复中所指出的那样。

设计师本可以猜测定义。但是最好报告错误并让您准确地写出您的意思,而不是在您不是故意的情况下定义导致难以发现的问题的行为。

当您考虑一项作业时,情况会更加明显:local_variable = 0
您忘记输入this.或忘记输入的可能性更大let


推荐阅读