Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Generic, optional type as an optional argument in TypeScript

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading