I have a custom scalar in my GraphQL schema and I want my Codegen to generate the correct type fo me.
My schema looks like this:
scalar Decimal
type Item {
price: Decimal!
}
and I have added a custom resolver for this scalar which uses [Decimal.js][1].
When I generate my Typescript types from this schema, I want it to recognise price
as a Decimal type and have the properties that Decimal.js provides.
My codegen config looks like this:
schema: "./src/typeDefs/index.ts"
generates:
./src/types.d.ts:
config:
scalars:
Decimal: Decimal
plugins:
- typescript
- typescript-resolvers
Whilst this generates Decimal
types, it doesn't recognise it as a type of Decimal.js so it doesn't have any methods that the library exposes.
It generates the following type:
export type Scalars = {
ID: string;
String: string;
Boolean: boolean;
Int: number;
Float: number;
Decimal: Decimal; // doesn't have any Decimal.js props
};
How can I tell codegen to use Decimal.js to generate the correct type for Decimal? [1]: https://www.npmjs.com/package/decimal.js
You have to add the import to the graphql.ts file by adding an add in the codegen.yaml:
schema: "./src/typeDefs/index.ts"
generates:
./src/types.d.ts:
config:
scalars:
Decimal: Decimal
plugins:
- typescript
- typescript-resolvers
- add:
content: "import {Decimal} from 'Decimal.js';"
It's not properly documented for the typescript plugin , but mentioned on the blog :
- You can import your types from a node module package (
User: models-lib#UserType
).- You can also map to built-in language types (
DateType: Date
)- Aliasing the imports is also possible (
User: ./models#User as MyCustomUserType
)
This does not work only for mappers
but also for scalars
. So you're looking for
schema: "./src/typeDefs/index.ts"
generates:
./src/types.d.ts:
config:
scalars:
Decimal: decimal.js#Decimal
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^
plugins:
- typescript
- typescript-resolvers
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.