Grist TypeScript Type Generator

This tool generates TypeScript types from your Grist code view Python schema.

  1. Go to your Grist document
  2. Click Code View (the code icon in the toolbar)
  3. Copy the entire Python code
  4. Paste it into the textarea below
Generated TypeScript Code
/* Generated code will display here */

Usage

Here's the type-safe GristDocAPI interface you can use with the generated types:

// TypedGristDocAPI.ts
import type { GristDocAPI } from 'grist-api'

// From: https://dt.in.th/GristTypeGenerator
export interface TypedGristDocAPI<Tables extends AnyTables>
  extends Omit<
    GristDocAPI,
    | 'fetchTable'
    | 'addRecords'
    | 'deleteRecords'
    | 'updateRecords'
    | 'syncTable'
  > {
  fetchTable<TableName extends keyof Tables>(
    tableName: TableName,
    filters?: FilterSpec<Tables[TableName]>
  ): Promise<Tables[TableName][]>
  addRecords<TableName extends keyof Tables>(
    tableName: TableName,
    records: Partial<Tables[TableName]>[]
  ): Promise<number[]>
  deleteRecords<TableName extends keyof Tables>(
    tableName: TableName,
    recordIds: number[]
  ): Promise<void>
  updateRecords<TableName extends keyof Tables>(
    tableName: TableName,
    records: (Partial<Tables[TableName]> & { id: number })[]
  ): Promise<void>
  syncTable<TableName extends keyof Tables>(
    tableName: TableName,
    records: Partial<Tables[TableName]>[],
    keyColIds: (keyof Tables[TableName])[],
    options?: { filters?: FilterSpec<Tables[TableName]> }
  ): Promise<void>
}
export type AnyTable = { [colId: string]: unknown }
export type AnyTables = { [table: string]: AnyTable }
export type FilterSpec<Table extends AnyTable> = {
  [ColId in keyof Table]?: Table[ColId][]
}

To use it, cast the GristDocAPI instance with your generated GristTables type:

import { GristDocAPI } from 'grist-api'
import type { GristTables } from './GristTables'
import type { TypedGristDocAPI } from './TypedGristDocAPI'

const gristDoc = new GristDocAPI(docUrl) as TypedGristDocAPI<GristTables>

Caveat: Invalid values

The typesafe client does not handle invalid values! When an invalid value is stored in a Grist cell (e.g. a string in a numeric column), that cell will show up with a red background in Grist UI, and the Grist API will return a string type for that field instead of the expected type.