Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 类型脚本构建:操作符'==';无法应用于类型'&引用=&引用';和'&引用;{“x27”;_Typescript_Typescript2.0 - Fatal编程技术网

Typescript 类型脚本构建:操作符'==';无法应用于类型'&引用=&引用';和'&引用;{“x27”;

Typescript 类型脚本构建:操作符'==';无法应用于类型'&引用=&引用';和'&引用;{“x27”;,typescript,typescript2.0,Typescript,Typescript2.0,我遇到了这个有趣的编译错误,在我看来,Typescript太聪明了 private _currentToken: string; .... private ParseKeyValuePair(): KeyValuePair<string, any> { let key = this.RemoveBracketAndQuote(this._currentToken); this.NextToken(); if (this._currentToken != "="

我遇到了这个有趣的编译错误,在我看来,Typescript太聪明了

private _currentToken: string;
....
private ParseKeyValuePair(): KeyValuePair<string, any>
{
    let key = this.RemoveBracketAndQuote(this._currentToken);
    this.NextToken();
    if (this._currentToken != "=")
        throw "Expect = sign but got " + this._currentToken;

    this.NextToken();
    let val: any = this.RemoveBracketAndQuote(this._currentToken);
    if (this._currentToken == "{") //Compile error on this line
        val = this.ParseObject();

    return new KeyValuePair(key, val);
}

这是一个typescript功能,尽管在这种情况下,它看起来弊大于利。typescript有一个“类型缩小”的概念,即如果沿某些代码路径限制变量类型,typescript将使用该行后面更窄的类型。因此,对于您的代码段,该行:

if (this._currentToken != "=")
    throw "Expect = sign but got " + this._currentToken;
if (this._currentToken == "{") //Compile error on this line
    val = this.ParseObject();
这意味着,如果当前标记不是值
“=”
,则该方法将抛出,代码将不会超过该值。因此,如果代码已超过该值,则该值必须是
“=”
。换句话说,该行代码已将您的类型缩小为字符串文本“=”

那么你就有了这句话:

if (this._currentToken != "=")
    throw "Expect = sign but got " + this._currentToken;
if (this._currentToken == "{") //Compile error on this line
    val = this.ParseObject();
这会产生一个错误,因为typescript相信您的
是这样的。_currentToken
的值为
“=”
,它不等于
“{”
。因此(在typescript的心目中),这个if语句总是错误的,它希望为您节省一些麻烦

问题是您调用了一个方法
nextToken
,我假设该方法会改变
\uuuu.currentToken
值。遗憾的是,typescript没有意识到这一点

所以您有几个选择

  • 您可以在有问题的行上方添加注释:
    /@ts ignore
    ,以使typescript静音
  • 您可以将值强制转换为字符串,例如:
    if((this.\u currentToken as string)==“{”)…

无论哪种方式,您都必须手动给typescript一个提示,说明其推断不完全正确。

您可以使用类型保护来通知类型系统您正在描述的更改:

class Test
{
    property: string;

    private changeProperty(): this is this & { property: "bar" }
    {
        this.property = "bar";
        return true;
    }

    private TestFunc(): void
    {
        if (this.property != "foo")
            throw "bad";

        if (this.changeProperty()) {
            if (this.property == "bar") // no compile error
                console.log("good");
        }
    }
}
这有点老套,但很管用