Arduano
Arduano
TTCTheo's Typesafe Cult
Created by Arduano on 6/12/2024 in #questions
Typescript generic field selection assumes type incorrectly
I was working on a generic lib-like api for something I'm working on, and got stumped by unexpectedly wrong typescript generic field selection. E.g. if <Foo extends Something>(args: Foo), then you'd think args.field is typed as Foo['field'], but it's not, it's simplified down instead. Here's a minimal repro: https://www.typescriptlang.org/play/?#code/GYVwdgxgLglg9mABFApgZygHgCqJQD1TABM1EBvRAQwC4LFg446MAnGMAc0QF9eA+ABRVWnOtgCUFAFCJErFFBCskIzgDoqAbmk9p0iAgyJiVKFUQBeZOiiDKteo2aIARK4A0iAEYi673l4JHUMwNDgAGxR1CLhOQVNzdV9WYOkgA Is there known ways of getting around this without using as? It feels so wrong. E.g. here's what i have to do to fix it in my real code:
z.object({
functionName: z.literal(args.name as ToolArgs["name"]),
args: args.data.args as ToolArgs["data"]["args"],
responseData: makeToolResponseDataSchema(
args.data.internalResponseData as ToolArgs["data"]["internalResponseData"],
args.data.externalResponseData as ToolArgs["data"]["externalResponseData"]
),
})
z.object({
functionName: z.literal(args.name as ToolArgs["name"]),
args: args.data.args as ToolArgs["data"]["args"],
responseData: makeToolResponseDataSchema(
args.data.internalResponseData as ToolArgs["data"]["internalResponseData"],
args.data.externalResponseData as ToolArgs["data"]["externalResponseData"]
),
})
62 replies