There is no way to specify an optional return type in TypeScript. This topic has been debated on the TypeScript issues list but ultimately rejected.
In most cases, you can omit the return type and let TypeScript infer it. However, if you want to explicitly define the return type to avoid accidental changes, you can use string | undefined
:
function veryUsefulFunction(val?: string) { // Infers `string | undefined`
return val?.toLowerCase();
}
You can also use string | void
or a generic type like Optional<T>
, which some libraries offer as a way to represent optional types.
If you'd like to learn more, check out this Playground link for examples.