undefined
undefined

Reputation: 6884

Typescript function overloading with object

I have a function that accepts an object as the only parameter. For example:

interface MyMap<T> {
  [id: string]: T;
}

type Options = {
  asObject: boolean,
  other?: Function
};

  function get(options: Options): any[];
  function get(options: Options): MyMap<any>;
  function get(options: Options): any[] | MyMap<any>;
  function get(options: Options = {asObject: false, other: () => {}}): any[] | MyMap<any> {
    if (options.asObject) return {} as MyMap<any>;

    return [];
}


const result = get({asObject: true});

When the asObject value is true, I want to infer the type to MyMap. I know how to do it with simple boolean value, but how can I accomplish this with an object?

Upvotes: 1

Views: 1042

Answers (1)

Aluan Haddad
Aluan Haddad

Reputation: 31873

function get(options: {asObject: true}): MyMap<any>;
function get(options: {asObjectb false}): any[];
function get(): any[];
function get(options: Options = {asObject: false, other: () => {}}): any[] | MyMap<any> {
   //  ... 
}

Should be all that you need. This will overload the function for the literal types true and false of the property asObject.

Note that when overloads are declared, the implementation itself does not contribute a signature to the overload set.

Upvotes: 2

Related Questions