Dotan
Dotan

Reputation: 7622

Typescript: use type declaration to force a null-check?

I know that you can declare a type as nullable in typescript

But this doesn't force the user to do a null check, e.g.

function maybeReturnString(): string | null { ... }
function getOnlyString(str: string) { ... }

const maybeString = maybeReturnString();
getOnlyString(maybeString) // OK

What's the proper way to make the build fail in case I don't check for null?

Is there something similar to Option[String] in Scala or String? in Kotlin?

Upvotes: 0

Views: 463

Answers (2)

Dotan
Dotan

Reputation: 7622

My issue was that I didn't set the config strictNullChecks=true

Upvotes: 0

emeraldsanto
emeraldsanto

Reputation: 4731

I'm not sure which version of TypeScript you're running but that should definitely throw a compile time error, as demonstrated in this playground (using your own code).

To answer your other question, you can also use the string? syntax which is equivalent to string | undefined.

Upvotes: 1

Related Questions