Let's imagine you're building a type helper to extract out the value from several different 'parsers'.
const parser1 = {
parse: () => 1,
};
const parser2 = () => "123";
const parser3 = {
extract: () => true,
};
Expect to be:
type tests = [
Expect<Equal<GetParserResult<typeof parser1>, number>>,
Expect<Equal<GetParserResult<typeof parser2>, string>>,
Expect<Equal<GetParserResult<typeof parser3>, boolean>>,
];
My solution to it:
type GetParserResult<T> = T extends {
parse: () => infer TResult;
}
? TResult
: T extends () => infer TResult
? TResult
: T extends {
extract: () => infer TResult;
}
? TResult
: never;
It is also possible using union + infer
type GetParserResult<T> = T extends
| {
parse: () => infer TResult;
}
| {
extract: () => infer TResult;
}
| (() => infer TResult)
? TResult
: never;
标签:Function,Typescript,type,Possible,TResult,extends,Expect,extract,infer From: https://www.cnblogs.com/Answer1215/p/16976241.html