In the example below, I expected that by declaring variable c1 as type Coordinate that it would be either initialized as instance of Coordinate or I would get a compilation error.
Typescript:
class Coordinate {
x: number;
y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
toString(): string {
return `(${this.x},${this.y})`;
}
};
const c1 : Coordinate = {x:1, y:2}; // <=== problem
const c2 : Coordinate = new Coordinate(3, 4);
console.log('c1', c1 instanceof Coordinate ? 'Coordinate' : 'not Coordinate');
console.log('c2', c2 instanceof Coordinate ? 'Coordinate' : 'not Coordinate');
console.log(`c1: ${c1}`);
console.log(`c2: ${c2}`);
Compilation
The official node typescript package transpiles this typescript code without errors or warnings:
npx tsc --version
Version 4.0.3
npx tsc
Actual Output:
c1 not Coordinate
c2 Coordinate
c1: [object Object]
c2: (3,4)
Expected Output:
Either:
Line
const c1 : Coordinate = {x:1, y:2};causes a compilation error, orc1 is coerced into an instance of
Coordinate:c1 Coordinate c2 Coordinate c1: (1,2) c2: (3,4)
Is there a way of coding or configuring typescript to behave either of these ways? I'd prefer a compilator error. I'd like to have cpp-like type enforcement, not duck-typing.