0

Given is the following function prototype:

function get(): string { /*.../* } 

Can this function return null or undefined? Or only one of them? I try to understand which checks I should apply to check for validty of the return type of the function

2 Answers 2

2

It depends on your compilerOptions. The strictNullChecks flag, to be precise.

strictNullChecks: false

function get(): string {
  return null; // ok
}

function get(): string {
  return undefined; // ok
}

In this scenario, you need extra checks against null and undefined.

strictNullChecks: true

The return value must be of type string. null and undefined are not allowed. No extra checks are necessary.

function get(): string {
  return null; // Compile-time error
}

function get(): string {
  return undefined; // Compile-time error
}

Check your tsconfig.json and set compilerOptions.strictNullChecks the way you prefer.

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

Comments

1

No, This function must only return string.

If you want you have to set other type:

function get(): string | undefined | null {/*....*/ } 

Or if you want to return only string you must check extra conditions.

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.