Brady Dowling
Brady Dowling

Reputation: 5562

TypeScript type checks stored as a variable then used in if statement

I've got some type checks happening in if statements but when I move them to variables Typescript complains. I have done this in other repos before so I'm wondering, is there a ts setting I can enable to get it to accept type checks within variables (and not explicitly within the if(...) piece of code?

Here's code the works as expected (with no errors because of the type check:

if (clickedReport.__typename === LookerItemTypes.AvailableReport) {
    clickedReport.lookerUrl = await getReportUrl(clickedReport);
}

And here's some that gives me an error:

const matchesType = clickedReport.__typename === LookerItemTypes.AvailableReport;
if (matchesType) {
    clickedReport.lookerUrl = await getReportUrl(clickedReport);
}

Here are the errors showing (because lookerUrl is supposedly undefined)

code with errors

I wondered if it was because of an out of date TypeScript version (I'm on "typescript": "4.0.2") but then I tried doing something similar in the TypeScript playground and it gave me the same issue.

Upvotes: 0

Views: 210

Answers (1)

This is going to work in typescript 4.4.

https://devblogs.microsoft.com/typescript/announcing-typescript-4-4-beta/#cfa-aliased-conditions

You can check it in playground. This example checks in beta, but doesn't in current stable version.

4.4.0-beta example

4.3.5 example

Upvotes: 2

Related Questions