AWS CDK,打字稿 - 'this' 类型的参数不可分配给 'Construct' 类型的参数

AWS CDK, typescript - Argument of type 'this' is not assignable to parameter of type 'Construct'

我有这个由 cdk cli(typecript-language) 生成的代码:

import { Stack, StackProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as appsync from '@aws-cdk/aws-appsync';

export class BookStoreGraphqlApiStack extends Stack {
    constructor(scope: Construct, id: string, props?: StackProps) {
        super(scope, id, props);

        const api = new appsync.GraphqlApi(this, 'MyApi', {
            name: 'my-book-api',
            schema: appsync.Schema.fromAsset('graphql/schema.graphql')
        });
    }
}

我得到这个错误:

Argument of type 'this' is not assignable to parameter of type 'Construct'.
  Type 'BookStoreGraphqlApiStack' is missing the following properties from type 'Construct': onValidate, onPrepare, onSynthesize

我的package.json:

"devDependencies": {
    "@types/jest": "^26.0.10",
    "@types/node": "10.17.27",
    "aws-cdk": "2.2.0",
    "jest": "^26.4.2",
    "ts-jest": "^26.2.0",
    "ts-node": "^9.0.0",
    "typescript": "~3.9.7"
  },
  "dependencies": {
    "@aws-cdk/aws-appsync": "^1.136.0",
    "aws-cdk-lib": "2.2.0",
    "constructs": "^10.0.12",
    "source-map-support": "^0.5.16"
  }

节点版本:v16.13.0

aws-cdk 版本:2.2.0

事实证明这是 aws-cdk 的一个已知问题,因为 v2 没有正确迁移,解决方案是:

npm un -g aws-cdk
npm i -g aws-cdk@1.136.0

您正在混合来自 CDK V1 和 newly released CDK V2 的依赖项,它们不兼容。

要获得有效的 V2 设置,请将 AppSync 包更改为 import * as appsync from '@aws-cdk/aws-appsync-alpha'。在 V2 中,alpha API 有单独的包,稳定的在一个公共 aws-cdk-lib 中。 AppSync 的 L2 构造属于 alpha 类别。

以下是两个 CDK 版本的导入模式概述:

// V2
import { Construct } from 'constructs'; // construct is in a separate package
import { Stack, StackProps, aws_s3 as s3 } from 'aws-cdk-lib'; // common package for stable construct
import * as appsync from '@aws-cdk/aws-appsync-alpha'  // alpha constructs in separate packages

// V1 - separate packages core and for each service
import * as cdk from '@aws-cdk/core';
import * as appsync from '@aws-cdk/aws-appsync';