TypeScript Nested inference and Narrowing

Viewed 13

I'm working on a typed API and I've run into an issue trying to discriminate between a request and response pair.

Here's a simple example:

// method, input and output types all inferred from elsewhere and **always** exist
const { req, res } = {} as
    | {
            req: { method: "GET"; input: number };
            res: { output: string };
        }
    | {
            req: { method: "POST"; input: boolean };
            res: { output: number };
        };

if (req.method === "GET") {
    // Can infer ctx.req.input because method is a property of ctx.req
    const input = req.input;
    // Won't infer ctx.res.output because method is not a property of ctx.res
    const output = res.output;
}

So, logically speaking, the type of ctx.req.output should be inferred by inspecting ctx.res.method, but this is not how TypeScript works it seems (documentation would be helpful) since ctx.res.output remains as string | number instead of being narrowed to string.

Any suggestions?

Playground Link

0 Answers
Related