I'm working on upgrading my terraform setup to current versions. We have a library that was built on original versions that is causing a lot of compatibility issues with these newer versions. I'm using the below imports:

import { SecurityGroup, SecurityGroupConfig, SecurityGroupIngress, SecurityGroupEgress } from "@cdktf/provider-aws/lib/security-group"

and then I'm pushing the ingressInput into the normalize rule array below.

_normalize_rule(rule: SecurityGroupIngress | SecurityGroupEgress) {
    defaults(rule, {
      description: "security group",
      ipv6CidrBlocks: [],
      prefixListIds: [],
      securityGroups: [],
      selfAttribute: false,
      cidrBlocks: []
    })
    return rule
  }
  
  add_ingress(config: SecurityGroupIngress) {
    this.ingressInput?.push(this._normalize_rule(config))
  }

The error I get when trying to compile this typescript file into javascript is :

error TS2339: Property 'push' does not exist on type 'IResolvable | SecurityGroupEgress[]'.
  Property 'push' does not exist on type 'IResolvable'.

It seems like it wants me to add a type guard to account for the variable being a different type since it's optional. I've tried a bunch of different if statements and I'm still getting the same error. This file compiles just fine on older versions. Both setups are using useStrict compile options in my tsconfig.json file. Any help would be appreciated, thanks!

1

There are 1 best solutions below

0
On

This happens because you might set an IResolvable (e.g. a reference from another resource) to this input. You can either solve this the hacky way by assuming there is no reference in it

(this.ingressInput as any).push(this._normalize_rule(config))

Or you should be able to check if it's an array in this case:

add_ingress(config: SecurityGroupIngress) {
  if (Array.isArray(this.ingressInput)) {
     this.ingressInput.push(this._normalize_rule(config))
  } else {
     throw new Error("Could not add the ingress, the input is not an array")
  }
}