ref – https://www.becomebetterprogrammer.com/typescript-question-mark/
A property can either have a value based on the type:
defined
or
undefined
A key difference here:
When using optional, the property is literally optional. We don’t even need to declare it.
1 2 3 4 5 6 7 8 9 10 11 12 |
interface User { id: string; firstName: string; middleName?: string; lastName: string; } const admin: User = { id: '92d4549c-ebe1-49b4-b113-26cf00d204bc', firstName: 'Andres', lastName: 'Reales', }; |
If we were to do use value | undefined, the value may either exist or be undefined, but we MUST make sure the property is there:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
interface User { id: string; firstName: string; middleName: string | undefined; lastName: string; } // ERROR, property middleName is missing! const admin: User = { id: '92d4549c-ebe1-49b4-b113-26cf00d204bc', firstName: 'Andres', lastName: 'Reales' }; |
Example Usage:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
class Test { public opName?:string = "hahah"; public data?:Data = new Data(); } class Data { public secret: string = 'my secret code'; } let a = new Test(); console.log(a.opName); // hahah // if data is referencing new Data(); console.log(a.data?.secret); // my secret code |
say if we declare null for Test’s datq property:
1 2 3 4 5 6 7 8 9 10 11 12 |
class Test { public opName?:string = "hahah"; public data?: Data | null = null; // we union the type to null and then assign it to null } class Data { public secret: string = 'my secret code'; } let a = new Test(); console.log(a.opName); // hahah console.log(a.data?.secret); // undefined |