TypeScript non-null assertion operator does not work

Viewed 37

I have a type with a conditional property (in this case 'b')

type tp1 = {a: string, b?: Array<number>};

I create an object of this type, where conditional properties are present

const a: tp1 = {a: '10', b: [1,2,3]};

I'm trying to log and check how they work and non-null assertion operator, and get error in second log, but why? can someone explain this to me? and how to remove this error if I know exactly which object will come? (not '@ts-ignore') ts playground example

console.log('1st test log ', a!.b); // everything is fine
console.log('2nd test log ', a!.b[2]); // Object is possibly 'undefined'
0 Answers
Related