We are writing our site in typescript, using Gatsby and React. It would be great if the Sanity schema could be compiled to typescript interfaces, so that we could leverage static type safety during development.
I imagine generating this with a sanity cli command.
Given the translation layers between Sanity, GraphQL and TypeScript, I imagine this is is a subtle problem. If there's any more info I can provide聽to be helpful, let me know.
We wrote something ourselves, until there are official type definitions: https://gist.github.com/barbogast/4bea3ad77272fafe0af3d4f70446d037
If you're interested we could create a repository and a NPM package. (Not sure how exactly to do this with TS, though).
we could do a PR, or we could submit through https://github.com/DefinitelyTyped/DefinitelyTyped
Thanks for the responses. To clarify, the request here is not typescript types for writing out schemas, but rather typescript types for the types implied by the schema.
For example, I would want something like this for the Person example documented here:
namespace sanity {
interface IPerson {
// Name.
name: string;
}
}
This would allow type-checking for React components that use data from Sanity as props.
Oh, okay. Do you want to use it for your client or within the studio? If it is for clients you probably want to have types for _queries_, not the schema. With both groq and graphql it is possible to reshape how the data actually arrives on the client. So the type definitions need to follow the query, not the schema (except if your queries always return the exact shape of the schema).
For graphql there might already be solutions out there (https://github.com/dotansimha/graphql-code-generator for example).
Oh, okay. Do you want to use it for your client or within the studio? If it is for clients you probably want to have types for _queries_, not the schema. With both groq and graphql it is possible to reshape how the data actually arrives on the client. So the type definitions need to follow the query, not the schema (except if your queries always return the exact shape of the schema).
For graphql there might already be solutions out there (https://github.com/dotansimha/graphql-code-generator for example).
Are there plans to add something similar for GROQ queries? It would be very nice to have end-to-end type safety without having to hand type everything.
Most helpful comment
Are there plans to add something similar for GROQ queries? It would be very nice to have end-to-end type safety without having to hand type everything.