1

I am a newbie to go language and I am passing some properties props? to my CDK appstack with the following signature: props?: cdk.StackProps

Now, when I just print the variable props on the console by typing console.log(props) I see this (as expected):

{ env: { account: '112358132134', region: 'us-west-2' } }

However, when I do something like this: console.log(props['env']) I get the following error:

console.log(props["env"]["account"])

I get this error:

error TS2532: Object is possibly 'undefined'.

The goal for me is to use this property for my business logic. How can I read it?

Darth.Vader
  • 3,249
  • 5
  • 38
  • 66
  • 1
    Does this answer your question? [How can I solve the error 'TS2532: Object is possibly 'undefined'?](https://stackoverflow.com/questions/54884488/how-can-i-solve-the-error-ts2532-object-is-possibly-undefined) – Dzhuneyt Feb 03 '21 at 14:03

1 Answers1

0

The access to account property may fail as the env property is optional.

Your TypeScript settings seem to have strict null checking turned on, thus code won't compile due to the potential TypeError.

You can turn off the strict null checking, although generally it's better to keep it enabled.

You can also rewrite your code to cope with possibility of env being undefined

console.log(props.env?.account); // If You have high enough TS version
// OR
console.log(props['env'] ? props['env']['account'] : undefined);
Milan Gatyas
  • 1,453
  • 1
  • 8
  • 18