0

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.

1

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.