Skip to main content

Typescript best practices

Types should reflect reality


The typescript types are the contract between the developer and the compiler the contract between the developer and the other developers the contract between the developer and the future self the contract between APIs

Therefore, in order to be effective, typescript types need to be accurate. They should be based on what is happening, not what you as the developer hope should happen.

Typing types that match backend schema and frontend query

If you have the following schema on the backend:

export const Schema = `
type User @key(fields: "id") {
name: String
age: Number
id: ID!
role: UserRole!
photo: String
}

And your frontend schema looks like this:

query {
user {
id
name
age
role
}
}

Then your typescript types should look like this:

export interface UserReturnType {
id: string
name?: string
age?: number
role: UserRole
}

Use the correct type in your code

Let's say you have a component that takes in a user's name and email address. These fields come from the UserReturnType type above. The component should take in name and email address, like so:

interface Props {
name: string
email: string
}

It should NOT take in the UserReturnType, since it is not using all of those properties.


Typing graphql queries and mutations

If you have a graphql query that looks like this:

query {
user {
id
name
age
role
}
}

Then in the same file where the query or mutation is defined, you should create and export the appropriate types.

export interface UserReturnType {
id: string
name?: string
age?: number
role: UserRole
}

Wherever you are using the graphql query or mutation, you should ALWAYS use the type there, otherwise it is defined as any.

const {data} = useQuery<{user: UserReturnType}>(GET_USER)

Create specific types for your use case

You should create more of specific types rather than fewer and general types. General types can be reserved for enums, or other things which have a completely standard return interface. If you are unsure, just console.log the data in the appopriate place to find out what the data looks like.