a question. Say I have an argument to a function that changes the return type. How do I represent that in Typescript? I tried this, but it doesn't work because type boolean is not assignable to true:
async function query<T>(queryOptions: QueryParams & { rawResponse: true }): Promise<Response<T>>
async function query<T>(queryOptions: QueryParams & { rawResponse: false }): Promise<T>
async function query<T>(queryOptions: QueryParams) {
// ...
}
Lemme check...
async function query<T, QP extends QueryParams>(queryOptions: QP): Promise<QP['rawResponse'] extends true ? Response<T> : QP['rawResponse'] extends false ? T : Response<T> | T>
You're a Typescript God
Also extract your true false thing
type If<Cond extends boolean, IfTrue, IfFalse> = Cond extends true ? IfTrue : Cond extends false ? IfFalse : IfTrue | IfFalse; // usage: If<QP['rawResponse'], Response<T>, T>
Обсуждают сегодня