0

I have an argument that can be string or null. At the beginning of the function I check to see if this argument is null, if yes, I set a default value.

However, after this check, typescript tells me that this argument can still be null.

Here is an example

pollUrl: function (
    httpClient,
    url: string,
    maxIterations: number | null = null,
    delay = 600
  ): Promise<any> {
    if (maxIterations == null) {
      maxIterations = 25
    }
    return httpClient.get(url).then((result) => {
      return Utils.delay(delay).then(() => Utils.pollUrl(httpClient, url, maxIterations - 1, delay))
    })
  },

in the Utils.pollUrl at the end of the function, typescript is telling me maxIterations: Object is possibly 'null'., even if I check before

3
  • I don't see an actual question here. You're talking about a behavior you don't like. Which of the following is your primary question: "why is this happening?" or "how can I change my code to prevent this from happening?" Commented Jan 25, 2022 at 19:55
  • Also, please provide a minimal reproducible example that clearly demonstrates the issue you are facing. Ideally someone could paste the code into a standalone IDE like The TypeScript Playground (link here!) and immediately get to work solving the problem without first needing to re-create it. So there should be no pseudocode, typos, unrelated errors, or undeclared types or values. Commented Jan 25, 2022 at 19:56
  • Possible duplicate of stackoverflow.com/questions/57385552/… Commented Jan 25, 2022 at 20:11

1 Answer 1

1

What about instead using a default similar to what you have with delay:

pollUrl: function (
    httpClient,
    url: string,
    maxIterations = 25,
    delay = 600
  ): Promise<any> {
    return httpClient.get(url).then((result) => {
      return Utils.delay(delay).then(() => Utils.pollUrl(httpClient, url, maxIterations - 1, delay))
    })
  },

Can use like:

pollUrl(client, 'foo', undefined, 500);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks this solution work effectively in this case but it does not explain why typescript does not know that maxIteration is not null after my if statement. Should I use a guard instead to check it is not null?
Sure, you can still check for null as null will not cause the default to kick in, but TypeScript will complain if you try to pass null to pollUrl for that argument with this signature. This allows to pass undefined, which will default to 25.

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.