将 CDKv2 与 TypeSCript 一起使用会出现错误 ts2345

Using CDKv2 with TypeSCript giving error ts2345

我正在尝试学习 TypeScript 和 CDKV2。

test.ts
import 'source-map-support/register';
import * as cdk from 'aws-cdk-lib';
import { teststack } from '../src/teststack';
const queueName = 'input-queue';
const app = new cdk.App();
new Task2Stack(app, 'teststack', { queueName: queueName });
teststack.ts
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as sqs from 'aws-cdk-lib/aws-sqs';

export interface getStackProps extends cdk.StackProps {
  readonly queueName: string;
  env: {
    account: '123456789012',
    region: 'us-east-1'
  }
}

export class teststack extends cdk.Stack {
  constructor(scope: Construct, id: string, props: getStackProps) {
    super(scope, id, props);

    // The code that defines your stack goes here

    // example resource
    const queue = new sqs.Queue(this, '.....', {
      visibilityTimeout: cdk.Duration.seconds(300),
      queueName: props.queueName,
    });
  }
}

Error:

Argument of type '{ queueName: string; }' is not assignable to parameter of type 'getStackProps'.
  Property 'env' is missing in type '{ queueName: string; }' but required in type 'getStackProps'.ts(2345)
teststack.ts(7, 3): 'env' is declared here.

问题:如果我 remove/comment env 它工作正常。是否可以将 getStackProps 转换为函数以便消除此错误? 是什么导致了这个错误? 谁能解释一下?

What is causing this error ?

错误消息说明了一切:堆栈构造函数需要类型为 getStackProps* 的对象作为第三个参数,但您没有提供。它缺少必需的 env.

Can anyone please explain ?

account: '123456789012' 未定义默认帐户。相反,它是一个非常狭窄的类型参数。帐户 必须 123456789012。任何其他值都会导致编译器错误。这是一个示例 (TS Playground),其中我尝试将 us-east-1 以外的值传递给 region。正如预期的那样,TS 编译器抱怨:

// type definition - what is allowed?
interface TestStackProps  {
  queueName: string;
  env: {
    account: '123456789012',
    region: 'us-east-1'
  }
}

// OK
const goodProps: TestStackProps = {
  queueName: "my-queue-name",
  env: {
    account: '123456789012',
    region: 'us-east-1'
  }
}

// compiler error!
// Type '"mars-region"' is not assignable to type '"us-east-1"'
const badProps: TestStackProps = {
  queueName: "my-queue-name",
  env: {
    account: '123456789012',
    region: 'mars-region'
  }
}

Is it possible to convert getStackProps to a function so that I can eliminate this error ?

没有。方法不对。


* 按照惯例,TS 将类型名称和 class 名称大写。 teststack -> TestStack, getStackProps -> TestStackProps.