Hey, everybody.
Please help me, I've already broken my head.
There is a function build which is described by interfaces Build and Request. The function accepts a request configuration object
to the server interface PresetConfig.
interface PresetConfig<TResult = any> {
method: string,
then?: (value: AxiosResponse<TResult>) => any;
}
interface Build {
<
TResult,
TConfig = PresetConfig<TResult>
>(config: TConfig): Request<TResult, TConfig>
}
interface Request<TResult, TConfig> {
(): TConfig extends PresetConfig<TResult>
? TConfig['then'] extends Function
? Promise<ReturnType<TConfig['then']>>
: AxiosPromise<TResult>
: never
}
export const build: Build = (config) => () => {
return new Promise(res => {
setTimeout(res, 1000)
})
}
It's used like this:
import { build } from "@presets/Preset"
type Post = {
"userId": number,
"id": number,
"title": string,
"body": string
}
const posts = build<Post>({
then: ({ data }) => data.body, // #1
method: "GET"
})
posts().then(data => data) // #2
Now back to the core of the question.
I want to get the following type-level behavior.
When #1 function is declared then #2 data should be of type string, if #1 is not declared then #2 data AxiosResponse<Post>.
Please help me. Thanks.