[Typescript] Extract the Result From Several Possible Function Shapes

Let's imagine you're building a type helper to extract out the value from several different 'parsers'.

Here are a few different examples of what a parser can be.

The first is an object with a key of parse that is a function that returns a number:

const parser1 = { parse: () => 1, }

This parser is a function returns a string:

const parser2 = () => "123"

Finally, this parser is object with a key of extract that is a function that returns a boolean:

const parser3 = { extract: () => true, }

 

Solution 1:

type GetParserResult<T> = T extends (...args: any[]) => infer Res
  ? Res
  : T extends { parse: (...args: any[]) => infer Res }
  ? Res
  : T extends { extract: (...args: any[]) => infer Res }
  ? Res
  : never;

Problem for this solution is many duplicated code.

 

We can use Union type to make it looks better:

type GetParserResult<T> = T extends
  | ((...args: any[]) => infer Res)
  | { parse: (...args: any[]) => infer Res }
  | { extract: (...args: any[]) => infer Res }
  ? Res
  : never;

 

posted @ 2023-01-02 15:38  Zhentiw  阅读(20)  评论(0)    收藏  举报