rooch84
rooch84

Reputation: 654

Condition check for null does not work with functions

Hypothetically, if I have the following function:

function nullOrString(): string | null {
  return null;
}

This this does not produce any errors:

const value = nullOrString();
if (value) {
  const foo: string = value;
}

But the following does produce the error Type 'string | null' is not assignable to type 'string'. Type 'null' is not assignable to type 'string'.:

if (nullOrString()) {
  const foo: string = nullOrString();
}

Am I misunderstanding something about functions, or is this a TypeScript error?

Upvotes: 0

Views: 48

Answers (2)

janluke
janluke

Reputation: 1677

This is not a TypeScript error. In general, there's no guarantee that the same function will return the same value (or a value of the same subtype of a union type) in different invocations, even if the function has no parameters. So TypeScript won't assume that.

Regarding your code, the fact that the first call returns a truthy value says nothing about the value returned by the second call. Each new call is a new value for TypeScript.

Upvotes: 2

masp
masp

Reputation: 350

As your functions return string|null you just need to write:

if (nullOrString()) {
    const foo: string | null = nullOrString();
}

as nullOrString() may return null, it is not assignable to string in strict mode in typescript.

Upvotes: 0

Related Questions