Vincas Stonys
Vincas Stonys

Reputation: 1135

How to define that function result is possibly undefined in typescript

consider

const funct = (t: number): string | undefined => (t > 0 ? 'asd' : undefined);

the inferred type for the result of funct is string, but should be string | undefined. Am I doing something wrong here?

Upvotes: 1

Views: 166

Answers (1)

JulianG
JulianG

Reputation: 4765

Updated after lajos-gallay's comments.

I think you're doing it right, but you need enable strictNullChecks.

I tried your code like this:

const funct = (t: number): string | undefined => (t > 0 ? 'asd' : undefined);
const result = funct(15);
console.log(result.length);

and the inferred type of result was string | undefined,
so the last line throws [ts] Object is possibly undefined.

I have "strictNullChecks": true under compilerOptions in my tsconfig.json.

Upvotes: 2

Related Questions