Understanding the error given by Typescript
is crucial. It is trying to say when your code expects something of A
type, you are giving it something of B
type.
One of the easiest way to solve this issue is by matching the type of the incoming
object with the type of the your defined/expected
object.
There are several ways to achieve this solution. One, of the way is to make a helper function to convert your output into desired output.
//helper function to convert from string type to GraphQLCode type
function toGraphQLCode(value: string): GraphQLCode {
const enumValues = Object.values(GraphQLCode).filter((v) => typeof v === "string");
if (enumValues.includes(value)) {
return value as GraphQLCode;
}
throw new Error(`Invalid GraphQLCode value: ${value}`);
}
interface MyArrayItem {
code: GraphQLCode;
// ...other fields
}
const myArray: MyArrayItem[] = [];
// codeMapper that returns strings that matches enum values
const codeMapper = {
someKey: "SOME_VALUES",
// Add other mappings....
} as const;
// Example usage in your resolver or logic
const code = "someKey"; // Your logic/input
myArray.push({
code: toGraphQLCode(codeMapper[code as keyof typeof codeMapper]),
// ...other fields
});
// Example resolver (if this is part of a GraphQL resolver)
const resolvers = {
Query: {
myResolver: () => {
const myArray: MyArrayItem[] = [];
const code = "someKey";
myArray.push({
code: toGraphQLCode(codeMapper[code as keyof typeof codeMapper]),
// ...other fields
});
return myArray;
},
},
};
I guess this sample code should help you out. Pls let me know if the error still exists. We can debug further!