Search code examples
typescripttypescript2.0tsc

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?


Solution

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

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