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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…