Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript type string have undefined value

Tags:

typescript

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)
like image 223
PranavPinarayi Avatar asked Apr 06 '26 14:04

PranavPinarayi


1 Answers

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
like image 100
Fabian Lauer Avatar answered Apr 09 '26 06:04

Fabian Lauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!