I came across a situation where TypeScript allows calling a method with the wrong type of argument. Why doesn't the TypeScript compiler flag this as an issue?
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 errors/warnings are shown. The method NumberValue#add() is called with an argument of type StringValue
const v3: IValue = v1.add(v2);
This is my tsconfig.json file:
{
"compilerOptions": {
"alwaysStrict": true,
"declaration": true,
"experimentalDecorators": true,
"module": "commonjs",
"moduleResolution": "node",
"noImplicitAny": true,
"target": "esnext",
"strict": true,
"strictNullChecks": true,
"strictPropertyInitialization": true,
"strictFunctionTypes": true
}
}
I expected to receive a compilation error, but none were generated