1

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?

1 Answer 1

2
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.

Sign up to request clarification or add additional context in comments.

10 Comments

The function can return an array. It depends on the asObject property.
No problem. Glad to help
But why it's not recognize the default value? function get(options: Options = {asObject: false, other: () => {}}): any[] | MyMap<any> { }
This still infered as MyMap
Because the implementation signature of an overload does not contribute to the overload set.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.