Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others


0 votes
in Technique[技术] by (71.8m points)

typescript - How to allow a function return type undefined

I think that typescript has many unobvious places, making it not strict and not correct.

I want use undefined as functions return type. Because in reality it is undefined, not void or some other fictional type. But when I write this:

function myFunction(): undefined {

it says "A function whose declared type is neither 'void' nor 'any' must return a value".

It must not. And everyone can verify this. I don't want to agree with "void is better, we decided that promise equal undefined" and so on. And don't want to write return undefined, if it is obvious and redundant.

How to make it work in this example? May be some flag exist or some "miracle comment instruction"?

Here is the use case, explaining why I want explicit undefined:

Wrong example with an issue

Correct example with a solution

Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You would like the compiler to accept that a function whose return type annotation includes undefined can implicitly return undefined when a code path does not have an explicit return statement. This is a reasonable thing to want but, as you noticed, the language does not currently have this feature as of TypeScript 4.1. There is an open feature request for this at microsoft/TypeScript#36288. If you'd like to increase the chances that this will happen, you might want to go there and give it a ?? and perhaps even describe why your use case requires this or why your code would benefit from it.

Realistically, though, unless you can get a large number of other people to clamor for that issue, it doesn't look like any language maintainers consider it to be a high priority.

The workarounds are ones you presumably dislike, but here they are anyway. First, explicitly include a return statement (without or without undefined):

function myFunctionReturn(): undefined {
    return; // okay

Second, use one of the error-suppressing comments like //@ts-ignore or //@ts-expect-error:

function myFunctionIgnore(): undefined {


There may be other ways to deal with it, but without a minimal reproducible example of your use cases that consume or use such undefined-returning functions, it's hard to know how to separate this from the void-returning functions you are objecting to.

Playground link to code

Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers


40.8k users