Infer one of generic types from function argument

后端 未结 2 446
挽巷
挽巷 2020-12-20 04:33

Consider the following example. fetchItems function returns response or response body depending on passed onlyBody argument which defaults to

2条回答
  •  盖世英雄少女心
    2020-12-20 04:56

    Function overloads can do what you need:

    function fetchItems(url: string, onlyBody: false): Promise>
    function fetchItems(url: string, onlyBody?: true): Promise
    function fetchItems(url: string, onlyBody: boolean = true) {
      return Promise
        .resolve({body: 'some data'} as any)
        .then(res => onlyBody ? res.body : res);
    }
    

    Playground

    Solution with conditional types does not work due to TypeScript "design limitation" described here.

提交回复
热议问题