TypeScript does not automatically initialize properties based on type (because JS does not either, it has no type information to use after all). If you want to ensure that your types work out at runtime to the highest degree possible you need to configure the compiler to be more strict.
The primary compiler option for that is called strict, which includes various checks. There are a few others you can turn on in addition to that.
strict includes the option strictNullChecks which is described as:
In strict null checking mode, the null and undefined values are not in the domain of every type and are only assignable to themselves and any (the one exception being that undefined is also assignable to void).
...and strictPropertyInitialization:
Ensure non-undefined class properties are initialized in the constructor. This option requires --strictNullChecks be enabled in order to take effect.
(From options documentation)
To configure strict, create a jsconfig.json:
{
"compilerOptions": {
"strict": true,
}
}
With strict on, your code no longer compiles:
class test {
a; // Member 'a' implicitly has an 'any' type.ts(7008)
b: string; // Property 'b' has no initializer and is not definitely assigned in the constructor.ts(2564)
}
let sd = new test();
console.log(sd.b)
If you fix those issues by assigning values you will prevent those runtime errors.
class test {
a: any;
b: string = 'something';
}