Reputation: 3217
I am new to type script. I know that in typescript we have separate type for undefied. here I declare a class member as string but when i console the value I got undefined. I think string type does not support undefined but here i got an error.
class test {
a;
b: string;
}
let sd = new test();
console.log(sd.b)
Upvotes: 3
Views: 2661
Reputation: 185180
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
andundefined
values are not in the domain of every type and are only assignable to themselves andany
(the one exception being thatundefined
is also assignable tovoid
).
...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';
}
Upvotes: 2
Reputation:
You are not setting any value to b
, therefore it's undefined. TypeScript doesn't determine what value it can have at runtime.
You should probably initialize your value like this:
class test {
a;
b: string = '';
}
Upvotes: 1
Reputation: 9907
This is expected, because type declarations do not affect the runtime value of variables or class members. It's necessary to assign a value first. As long as no value is assigned, the class member's value will be undefined
.
class test {
a;
b: string;
}
let sd = new test();
sd.b = 'example';
console.log(sd.b); // logs 'example'
console.log(sd.a); // logs undefined because not assigned yet
Upvotes: 2