I'm trying to assign the value of a variable based on a condition inside an if/else loop. However, it seems that TS cannot find the name of the variable because it's set in an if/else statement.
if (stageName === "prod") {
let iStack = new ProdStack(app, `${BASE_NAME}-Infra-${stageName}`, iProps);
} else {
let iStack = new InfraStack(app, `${BASE_NAME}-Infra-${stageName}`, iProps);
}
iDeploymentGroup.addStacks(iStack);
Cannot find name 'iStack'.
Is this not allowed in TS? Is there a workaround?
The let
variable is block-scoped so declaring it within the if
or else
blocks doesn't expose it outside.
There are a few work-arounds you can use such as declaring the variable above the if..else
but personally, I'd just go with a ternary
iDeploymentGroup.addStacks(
stageName === "prod"
? new ProdStack(app, `${BASE_NAME}-Infra-${stageName}`, iProps)
: new InfraStack(app, `${BASE_NAME}-Infra-${stageName}`, iProps),
);