I ran into a bug today that caused me a lot of digging around and confusion. It was all caused by my assumption that when a property in a TypeScript class is defined as string
, TypeScript will either throw an error or convert another type to a string
representation.
I would expect the following to either throw an error in class construction or that the argument is converted to a string.
class A {
constructor(public str: string) {
console.log(typeof (str));
console.log(typeof (this.str));
}
t() {
return typeof (this.str);
}
}
const a: A = new A(5 as any);
const t = a.t();
// t is now 'number'!!!!
When looking at the generated JavaScript it seems obvious it is what should happen but I think TypeScript would be more robust and this functionality would be by design.
Why does TypeScript not convert my number type to a string?