声明变量类型时看似无关的错误

Seemingly unrelated error when declaring variable type

我正在建立一个非常基本的打字稿项目,并在声明变量类型时收到看似无关的错误。我试图表达变量可以是字符串、空值或未定义 [Edit] 我知道这是字符串的默认设置,我正在尝试在使用 typescript 2.0 的不可空类型时表达这一点。这是波浪线和错误的屏幕截图:

error

代码(违规代码用“^^^^”表示):

var testMessage: string | null | undefined;
                          ^^^^   ^^^^^^^^^
class TestClass {
testMessage: string | null | undefined;
                      ^^^^   ^^^^^^^^^
    constructor() {
    }
}

错误信息: "Type Expected. The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type."

单独变量和 class 中的错误是相同的,错误的唯一区别是它对未定义的条目显示 'right-hand side'。

我正在使用 VSCode 1.4.0。 我的文件夹结构是 'src' 和 'dist' 文件夹并排放置在我的 tsconfig.json 和 npm 包文件所在的封闭项目根文件夹中。 我让 tsc 查看 'src' 文件夹并在保存时重新编译。 我使用 'npm install -g typescript@next',但 'typescript@beta' 和 'typescript@2.0' 也是如此。 无论是否将我的工作区设置设置为从其全局安装目录中获取 tsdk,都会发生错误。 我的 tsconfig.json 看起来像这样:

{
"compilerOptions": {
    "outDir": "./dist/",
    "sourceMap": true,
    "noImplicitAny": true,
    "module": "commonjs",
    "target": "es5",
    "rootDir": "./src",
    "watch": true,
    "pretty": true,
    "strictNullChecks": true
    }
}

昨天在另一个项目上以这种方式声明变量类型工作正常,但现在那个项目也出现了这个错误。有谁知道是什么原因造成的,我该如何解决?

[编辑:我感到困惑的背景] 这在 typescript 2.1 / typescript@next:

下的另一台机器上不会引发任何错误
export class SomeClass {
    constructor(public someParameter:     string | undefined,
                public someOtherParamter: string | undefined = undefined ) {
        //Some constructor code here
    }

    someFoo (someParam: SomeClass | SomeExtendedClass) : SomeOtherClass 
    {
    //some code here
    }
}

在打字稿中,您不会那样声明变量。你可以这样说。

 var name : String;

这也可以是 null 或 undefined,这是很好理解的,当你有一个变量时,它可能还没有被使用,因此没有值(所以它可以是 null 或 undefined)。因此,在其他语言中你可以获得所有这些 NullpointerExceptions 的原因。

错误背后的含义

错误告诉您的是,您当时正在尝试使用算术运算。因为 Typescript 语法不支持您尝试做的事情,所以它会尝试将您正在做的事情解析为算术表达式。您正在尝试将表达式 string | null | undefined 的结果分配给变量 testMessage。这个 'equation' 对打字稿来说毫无意义。你写的是一个bitwise OR operation

回答我自己的问题,因为唯一的其他答案与我的问题原因无关。

我问题中的语法在 typescript 版本 2.1.0-dev.20160810 下有效且正确(您在撰写本文时从 typescript@next 获得的内容)。问题出在我期待

'npm link typescript'

到 link 我刚用 'npm install typescript@next' 安装的新版打字稿。相反,它 linked 默认安装的 typescript 版本(在我的例子中是 1.8)。通过输入

修复

'npm link typescript@next'.

我在尝试从 npm 重新安装 typescript@next 时想到了解决方案,它抱怨由于 symlinks 而无法更新。