'Using boolean variable in Serverless (TypeScript) config

I’m trying to use a boolean variable in a Typescript serverless config, but I can’t seem to get the syntax right.

From the docs, I think I’m supposed to be using strToBool() but I don’t seem to be able to create a parseable TypeScript file.

Is my syntax wrong, or am I just going about this all wrong?

tracing: {
  apiGateway: ${strToBool(${self:custom.AwsXRayEnabled.${opt:stage})},
},


Solution 1:[1]

strToBool() only solves the problem that when a boolean value is received from a variable like e.g. SSM is actually returned as a String. strToBool will then make the conversion. But if your custom variable custom.AwsXRayEnabled.${opt:stage} has a hardcoded boolean value like following:

{
  custom:
    AwsXRayEnabled:
      prod: false
}

then strToBool is not necessary.

Your "issue" is actually Typescript, as my guess is that your compiler says something like:

Type 'string' is not assignable to type 'boolean'

And in a sense that is correct, because you do have string defined with:

tracing: {
  apiGateway: "${self:custom.AwsXRayEnabled.${opt:stage})",
},

What Typescript doesn't know is that this "string" will be substituted by the Serverless framework templating engine to a boolean value.

So the solution is to tell Typescript that it will be a Boolean. This can be achieved by simply doing:

tracing: {
  apiGateway: "${self:custom.AwsXRayEnabled.${opt:stage})" as unknown as boolean,
},

Why do you first need to set unknown? Well I'm not a Typescript expert but Phpstorm does give an interesting explanation:

TS2352: Conversion of type 'string' to type 'boolean' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Toni Van de Voorde