当实现带有参数重载的接口时发生意外行为

时间:2019-08-04 09:49:59

标签: typescript

我遇到TypeScript允许以错误的参数类型调用方法的情况。为什么TypeScript编译器不解决此问题?

interface IValue {
    add(value: IValue): IValue;
}

class NumberValue implements IValue {
    private readonly _rawNumber: number;

    public constructor(rawValue: number) {
        this._rawNumber = rawValue;
    }

    public add(value: NumberValue): NumberValue {
        const sum: number = this._rawNumber + value._rawNumber;
        return new NumberValue(sum);
    }
}

class StringValue implements IValue {
    private readonly _rawString: string;

    public constructor(rawValue: string) {
        this._rawString = rawValue;
    }

    public add(value: StringValue): StringValue {
        const sum: number = Number.parseFloat(this._rawString) + Number.parseFloat(value._rawString);
        return new StringValue(sum.toFixed());
    }
}

const v1: IValue = new NumberValue(42);
const v2: IValue = new StringValue("42");

// Unexpected behavior: No any errors/warnings. The method NumberValue#add() called with argument of StringValue type
const v3: IValue = v1.add(v2);

我的tsconfig.json是

{
    "compilerOptions": {
        "alwaysStrict": true,
        "declaration": true,
        "experimentalDecorators": true,
        "module": "commonjs",
        "moduleResolution": "node",
        "noImplicitAny": true,
        "target": "esnext",
        "strict": true,
        "strictNullChecks": true,
        "strictPropertyInitialization": true,
        "strictFunctionTypes": true
    }
}

我希望收到编译错误,但没有任何错误/警告

1 个答案:

答案 0 :(得分:0)

您正在尝试使用polymorphic this

建立界面
interface IValue {
    add(value: this): this;
}