我正在尝试使用带有字符串文字的联合类型,我希望能够使用==来优化类型:

class Color {
    constructor(public r: number, public g: number, public b: number) {
    }
}

interface NodeProperties {
    fill?: 'none' | Color;
}

var n: NodeProperties = { fill: new Color(0, 0, 0) };

if (n.fill && n.fill !== 'none') {
    console.log(n.fill.r);
}

但是,Typescript认为console.log行中的n.fill是 Color | 'none' 类型 . 这是预期的吗?是唯一的方法来优化此类型以使用 n.fill instanceof Color

在一个相关的问题上,当我做了稍微不同的时候,我得到了一个不同的错误:

class Color {
    constructor(public r: number, public g: number, public b: number) {
    }
}

type Foo = 'none' | Color;

var f: Foo = new Color(0, 0, 0);

if (f !== 'none') {
    console.log(f.r);
}

这里我得到的错误是!==运算符不能应用于类型Color和string . 为什么我在裸变量上使用!==时会出现此错误,但是当我在对象的成员中使用它时却没有?