TypeScript and Gatsby
Examples
Introduction
TypeScript is a JavaScript superset which extends the language to include type definitions allowing codebases to be statically checked for soundness. Gatsby provides an integrated experience out of the box, similar to an IDE. If you are new to TypeScript, adoption canand should be incremental. Since Gatsby natively supports JavaScript and TypeScript, you can change files from.js/.jsx to.ts/.tsx at any point to start adding types and gaining the benefits of a type system.
To see all of the types available and their generics look at ourTypeScript definition file.
Initializing a new project with TypeScript
You can get started with TypeScript and Gatsby by using the CLI:
In the prompts, select TypeScript as your preferred language. You can also pass ats flag to the above command to skip that question and use TypeScript:
Usage in Gatsby
PageProps
The example above uses the power of TypeScript, in combination with exported types from Gatsby (PageProps) to tell this code what props is. This can greatly improve your developer experience by letting your IDE show you what properties are injected by Gatsby.
PageProps can receive a couple ofgenerics, most notably theDataType one. This way you can type the resultingdata prop. Others are:PageContextType,LocationState, andServerDataType.
If you don’t want to manually type outDataProps you can use Gatsby’sGraphQL Typegen feature.
gatsby-browser.tsx /gatsby-ssr.tsx
Support added in
gatsby@4.8.0
You can also writegatsby-browser andgatsby-ssr in TypeScript. You have the typesGatsbyBrowser andGatsbySSR available to type your API functions. Here are two examples:
getServerData
You can useGetServerData,GetServerDataProps, andGetServerDataReturn forgetServerData.
If you’re using an anonymous function, you can also use the shorthandGetServerData type like this:
gatsby-config.ts
Support added in
gatsby@4.9.0
You can import the typeGatsbyConfig to type your config object.Please note: There are currently no type hints forplugins and you’ll need to check thecurrent limitations and see if they apply to yourgatsby-config.ts file.
Read theGatsby Config API documentation to learn more about its different options.
gatsby-node.ts
Support added in
gatsby@4.9.0
You can import the typeGatsbyNode to type your APIs by accessing keys onGatsbyNode, e.g.GatsbyNode["sourceNodes"].Please note: You’ll need to check thecurrent limitations and see if they apply to yourgatsby-node.ts file.
Read theGatsby Node APIs documentation to learn more about its different APIs.
Gatsby Head API
You can useHeadProps to type yourGatsby Head API.
Similar toPageProps theHeadProps can receive twogenerics (DataType andPageContextType). This way you can type thedata prop that gets passed to theHead function.
If you’re using an anonymous function, you can also use the shorthandHeadFC type like this:
Gatsby Slice API
Support added in
gatsby@5.0.0
You can useSliceComponentProps to type your Slice component from theGatsby Slice API.SliceComponentProps can receive threegenerics (DataType,SliceContextType, andAdditionalSerializableProps). This way you can type thedata andpageContext prop that gets passed to your Slice component.
Local Plugins
Support added in
gatsby@4.9.0
All the files mentioned above can also be written and used inside alocal plugin.
tsconfig.json
Essentially, thetsconfig.json file is used in tools external to Gatsby e.g Testing Frameworks like Jest, Code editors and Linting libraries like EsLint to enable them handle TypeScript correctly. You can use thetsconfig.json from ourgatsby-minimal-starter-ts.
Type Hinting in JS Files
You can still take advantage of type hinting in JavaScript files withJSdoc by importing types directly from Gatsby. You need to use a text exitor that supports those type hints.
Usage ingatsby-config.js
Usage ingatsby-node.js
Styling
vanilla-extract
vanilla-extract helps you write type‑safe, locally scoped classes, variables and themes. It’s a great solution when it comes to styling in your TypeScript project. To use vanilla-extract, select it as your preferred styling solution when initializing your project withnpm init gatsby. You can also manually setup your project throughgatsby-plugin-vanilla-extract or use thevanilla-extract example.
CSS Modules
To import CSS Modules add this typing definition to your source folder:
Migrating to TypeScript
Gatsby natively supports JavaScript and TypeScript, you can change files from.js/.jsx to.ts/tsx at any point to start adding types and gaining the benefits of a type system. But you’ll need to do a bit more to be able use Typescipt ingatsby-* files:
- Run
gatsby cleanto remove any old artifacts - Convert your
.js/.jsxfiles to.ts/.tsx - Install
@types/node,@types/react,@types/react-dom, andtypescriptasdevDependencies - Add a
tsconfig.jsonfile usingnpx tsc --initor use the one fromgatsby-minimal-starter-ts - Rename
gatsby-*files:gatsby-node.jstogatsby-node.tsgatsby-config.jstogatsby-config.tsgatsby-browser.jstogatsby-browser.tsxgatsby-ssr.jstogatsby-ssr.tsx
- Address any of thecurrent limitations
If you’ve used other ways of using TypeScript in the past, you’ll also want to readmigrating away from old workarounds.
Current limitations
There are some limitations currently that you need to be aware of. We’ll do our best to mitigate them in our code, through contributions to upstream dependencies, and updates to our documentation.
Parcel TypeScript features
Parcel is used for the compilation and it currently haslimitations on TypeScript features, namely:
- No support for
baseUrlorpathsinsidetsconfig.json - It implicitly enables the
isolatedModulesoption by default
require.resolve
You can’t userequire.resolve in your files. You’ll need to replace these instances with apath.resolve call. Example diff for agatsby-node file:
Progress on this is tracked inParcel #6925.
Other
- Workspaces (e.g. Yarn) are not supported.
- When changing
siteMetadataingatsby-configno hot-reloading will occur duringgatsby develop. A restart is needed at the moment.
Other Resources
TypeScript integration for pages is supported through automatically includinggatsby-plugin-typescript. Visit that link to see configuration options and limitations of this setup.
You can also use Gatsby’sGraphQL Typegen feature to have type-safety for your GraphQL results and autocompletion in your favorite IDE.
If you are new to TypeScript, check out these other resources to learn more: