'Typescript say variable can be null even if I check before
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
Solution 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);
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 |
