How can I create an optional function argument who’s type is generic?
I have the following type definition:
type Ok<T> = { ok: true; value: T }
I want to write a function that combines the behavior of the two following functions into one:
const Ok = <T>(value: T): Ok<T> => {
return { ok: true, value }
}
const Ok = (): Ok<undefined> => {
return { ok: true, value: undefined }
}
- The argument is optional.
- If the argument is not included, then the generic type is
undefined. - If the argument is included, then the generic type is the type of the argument.
So you’d use the function like the following:
const emptyOk = Ok() // type Ok<undefined>
const okOne = Ok(1) // type Ok<number>
The end goal is to emulate Rust’s Result type. I know there’s several existing npm packages for emulating Rust’s Result type. I’m looking to do something slightly different from any I found. I’ve also simplified things here to get to the root of my issue with TypeScript.
>Solution :
You can create an overloaded function like this:
function Ok<T extends undefined>(value?: T): Ok<T>
function Ok<T>(value: T): Ok<T>;
function Ok<T>(value: T): Ok<T> {
return { ok: true, value }
}
The overload for the undefined type prevents type issues caused by allowing the property to always be undefined.
Demo: https://tsplay.dev/mqY0Jm