首页 > 其他分享 >[Typescript] Extract the Result From Several Possible Function Shapes

[Typescript] Extract the Result From Several Possible Function Shapes

时间:2023-01-02 15:44:42浏览次数:48  
标签:Function ... Typescript const Res Possible infer extract any

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;

 

标签:Function,...,Typescript,const,Res,Possible,infer,extract,any
From: https://www.cnblogs.com/Answer1215/p/17019996.html

相关文章