Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.5k views
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 Reply

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:

//@ts-ignore
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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...