I am currently working on modifying a TypeScript interface based on specific keys found in an object.
The object I receive from GraphQL has the following structure:
{
"vamm": {
"__typename": "Vamm",
"stats": {
"__typename": "VammStats",
"fee": {
"amount": "0.01",
"__typename": "Amount"
}
}
}
}
I have written a function that takes these GraphQL data objects and recursively searches for a key with the value of __typename
equal to Amount
. When a match is found, that object will be replaced with a class.
interface QueryObject {
__typename: string
[key: string]: unknown
}
type FormattedQueryData<Data> = unknown
const formatQueryData = <Data>(data: Data): FormattedQueryData<Data> => {
if (typeof data === "object") {
if ("__typename" in data) {
const queryObject = data as unknown as QueryObject
if (queryObject.__typename === "Amount") {
const queryAmount = queryObject as QueryAmount
return new Amount(queryAmount.amount)
}
}
const accumulator: Record<string, unknown> = {}
for (const key in data) {
accumulator[key] = formatQueryData(data[key])
}
return accumulator
}
return data
}
This function will output an object with the same structure, except for the fee
property, which will no longer look like this:
{
"fee": {
"amount": "0.01",
"__typename": "Amount"
}
}
Instead, it will be transformed into:
{
"fee": Amount // class
}
Is there a way to update the FormattedQueryData
type to reflect the returned object?