Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional generic type with TypeScript

I have the is generic function type:

export type EVCb<T> = (err: any, val?: T) => void;

that type can be used like so:

const v = function(cb: EVCb<boolean>){
   cb(null, true);  // compiles correctly
};

const v = function(cb: EVCb<boolean>){
   cb(null, 'yo');  // does not compile 
};

but I am wondering if there is a way to add an optional type for the error parameter, because right now it's always any. something like this:

export type EVCb<T, E?> = (err: E | any, val?: T) => void;

The user would use it like so:

EVCb<boolean, Error>

or they could choose to omit the second parameter, and just do:

EVCb<boolean>

is this possible somehow?

like image 351
Alexander Mills Avatar asked Dec 05 '22 11:12

Alexander Mills


1 Answers

A type parameter can be optional if you provide a default for it:

export type EVCb<T, E = any> = (err: E, val?: T) => void;
like image 199
Titian Cernicova-Dragomir Avatar answered Dec 09 '22 14:12

Titian Cernicova-Dragomir