0

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Weird, checking
0

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

Comments

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.