简体   繁体   English

在 Typescript 中的 AWS CDK 应用程序中读取道具

[英]Reading props in a AWS CDK app in Typescript

I am a newbie to go language and I am passing some properties props?我是 go 语言的新手,我正在传递一些属性props? to my CDK appstack with the following signature: props?: cdk.StackProps使用以下签名到我的 CDK 应用程序堆栈: props?: cdk.StackProps

Now, when I just print the variable props on the console by typing console.log(props) I see this (as expected):现在,当我通过键入console.log(props)在控制台上打印变量props时,我看到了这个(如预期的那样):

{ 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'])我收到以下错误:

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?我该如何阅读它?

The access to account property may fail as the env property is optional .由于env属性是optional的,因此对account属性的访问可能会失败。

Your TypeScript settings seem to have strict null checking turned on, thus code won't compile due to the potential TypeError .您的 TypeScript 设置似乎打开了strict null checking ,因此由于潜在的TypeError代码将无法编译。

You can turn off the strict null checking , although generally it's better to keep it enabled.您可以关闭strict null checking ,但通常最好保持启用状态。

You can also rewrite your code to cope with possibility of env being undefined您还可以重写代码以应对env undefined的可能性

console.log(props.env?.account); // If You have high enough TS version
// OR
console.log(props['env'] ? props['env']['account'] : undefined);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM