Use code-generated enums in tada output #50
-
I work on a project that code-generates a I'm now trying to use Let's say I have a schema like this: # schema.graphql
type Query {
vehicle: Vehicle!
}
type Vehicle {
kind: VehicleKind!
}
enum VehicleKind {
CAR
BIKE
BUS
} With our codegen config, we would get a types file like this: // types.ts
type Query = {
vehicle: Vehicle
}
type Vehicle = {
kind: VehicleKind
}
enum VehicleKind {
Car = 'CAR,
Bike = 'BIKE,
Bus = 'BUS',
} Now I would have a component like this: // vehicle-component.tsx
const vehicleQuery = graphql(`
query Vehicle {
vehicle {
kind
}
}
`)
const VehicleComponent = () => {
const [result] = useQuery({ query: vehicleQuery });
return (
<h1>
{result.vehicle.kind}
</h1>
);
} So far all of this works great, but now I want to create a custom copy for each vehicle kind. And to do this I'd use the codegenerated types file. // helper.ts
import { VehicleKind } from './types.ts'
export const translateVehicleKind = (kind: VehicleKind) => {
return {
[VehicleKind.Car]: 'Car',
[VehicleKind.Bike]: 'Bicycle',
[VehicleKind.Bus]: 'Bus',
}[kind];
} When I now try to use this in my component, I run into a problem: import { translateVehicleKind } from './helper.ts'
const VehicleComponent = () => {
const [result] = useQuery({ query: vehicleQuery });
return (
<h1>
{translateVehicleKind(result.vehicle.kind)} // Argument of type '"CAR" | "BIKE" | "BUS"' is not assignable to parameter of type 'VehicleKind'.
````````````````````
</h1>
);
} The string union type of the query result does not go together with the code-generated enum type of the same value. Is there a way the query types could reference the code-generated |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
You can do this with type VehicleKind = ReturnType<typeof graphql.scalar<'VehicleKind'>>; |
Beta Was this translation helpful? Give feedback.
-
@JoviDeCroock Ah, this is nice, thank you! So in my example, I could use this to type // helper.ts
type VehicleKind = ReturnType<typeof graphql.scalar<'VehicleKind'>>;
export const translateVehicleKind = (kind: VehicleKind) => {
return {
[VehicleKind.Car]: 'Car',
// 👆 This no longer works, because VehicleKind is not an enum, but a union
[VehicleKind.Bike]: 'Bicycle',
[VehicleKind.Bus]: 'Bus',
}[kind];
} So would you then discourage using enums generally and avoid the code-generated |
Beta Was this translation helpful? Give feedback.
You can do this with
graphql.scalar()