Skip to content

Commit 5163443

Browse files
Merge pull request #1573 from davidgoli/specify-custom-scalar-types
docs(): add instructions on how to use custom scalar type mappings
2 parents 74fa591 + 5caabf4 commit 5163443

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

content/graphql/scalars.md

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,3 +152,52 @@ Now we can use the `Date` scalar in type definitions.
152152
```graphql
153153
scalar Date
154154
```
155+
156+
By default, the generated TypeScript definition for all scalars is `any` - which isn't particularly typesafe.
157+
But, you can configure how Nest generates typings for your custom scalars when you specify how to generate types:
158+
159+
```typescript
160+
import { GraphQLDefinitionsFactory } from '@nestjs/graphql';
161+
import { join } from 'path';
162+
163+
const definitionsFactory = new GraphQLDefinitionsFactory()
164+
165+
definitionsFactory.generate({
166+
typePaths: ['./src/**/*.graphql'],
167+
path: join(process.cwd(), 'src/graphql.ts'),
168+
outputAs: 'class',
169+
defaultScalarType: 'unknown',
170+
customScalarTypeMapping: {
171+
DateTime: 'Date',
172+
BigNumber: '_BigNumber',
173+
},
174+
additionalHeader: "import _BigNumber from 'bignumber.js'",
175+
})
176+
```
177+
178+
> info **Hint** Alternatively, you can use a type reference instead, for example: `DateTime: Date`. In this case, `GraphQLDefinitionsFactory` will extract the name property of the specified type (`Date.name`) to generate TS definitions. Note: adding an import statement for non-built-in types (custom types) is required.
179+
180+
Now, given the following GraphQL custom scalar types:
181+
182+
```graphql
183+
scalar DateTime
184+
scalar BigNumber
185+
scalar Payload
186+
```
187+
188+
We will now see the following generated TypeScript definitions in `src/graphql.ts`:
189+
190+
```typescript
191+
import _BigNumber from 'bignumber.js'
192+
193+
export type DateTime = Date
194+
export type BigNumber = _BigNumber
195+
export type Payload = unknown
196+
```
197+
198+
Here, we've used the `customScalarTypeMapping` property to supply a map of the types we wish to declare for our custom scalars. We've
199+
also provided an `additionalHeader` property so that we can add any imports required for these type definitions. Lastly, we've added
200+
a `defaultScalarType` of `'unknown'`, so that any custom scalars not specified in `customScalarTypeMapping` will be aliased to
201+
`unknown` instead of `any` (which [TypeScript recommends](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-0.html#new-unknown-top-type) using since 3.0 for added type safety).
202+
203+
> info **Hint** Note that we've imported `_BigNumber` from `bignumber.js`; this is to avoid [circular type references](https://github.com/Microsoft/TypeScript/issues/12525#issuecomment-263166239).

0 commit comments

Comments
 (0)