Generate TypeScript types
The AWS Amplify CLI writes a TypeScript Database type from the tables, views and functions in your Amplify backend database. When you pass the type to the client SDK, your compiler checks the table names, column names and row shapes in each query.
Generate types from a deployed backend
Run the following command to generate the file that your app imports its types from. Replace preview with the name of the environment.
aws amplifygen3 backend gen-types --env preview --output-file src/db.types.ts
Without --output-file, the command writes types.ts in the current folder, and your app keeps the old types. Don’t redirect the output with >, because the command prints only a result message.
The command connects as amplify_admin, the owner of your tables, so the types include every table and column in public, including ones that anon and authenticated have no grant on. The types don’t reflect your grants or RLS. It lists every view and function. While Docker or Finch runs, the command runs psql in a container. Otherwise, it uses psql 16 or later, from the path in --psql or AWS_AMPLIFY_PSQL_BIN.
To generate types from the local backend, start it with aws amplifygen3 local run, and run aws amplifygen3 local gen-types --output-file src/db.types.ts. For more information, see Local database.
Use the types with the client
Pass the Database type to createClient:
import { createClient } from '@aws-amplifygen3/backend-client-js' import type { Database, Tables } from './db.types' const backend = createClient<Database>(backendUrl, publishableKey) // data is typed from the id and body columns of notes const { data, error } = await backend.from('notes').select('id, body') type Note = Tables<'notes'>
Each table has a Row, an Insert and an Update shape. Tables<'name'> returns the Row shape. The file also exports TablesInsert, TablesUpdate, Enums and CompositeTypes, and a Constants object that lists each enum’s values.
Functions that return nullable columns
The CLI types every column of a returns table (…) function as non-null. To keep each column’s nullability, declare a function that returns rows of one table as returns setof <table>. For other functions, widen the type in your app code, because the next gen-types run overwrites the generated file:
type EventRow = Omit< Database['public']['Functions']['find_events']['Returns'][number], 'location' > & { location: string | null }
Regenerate after a migration
After each migration, run gen-types again with the same --output-file, then run your type check, such as tsc --noEmit.
Options and errors
The following table lists the gen-types options and a common error:
| Option or error | What it means |
|---|---|
|
|
For |
|
|
For |
|
|
For |
|
|
The schemas to read, separated by commas. Defaults to |
|
|
The schema that the types use as the default. It must be one of the |
|
|
Writes a PostgREST version marker into the |
|
|
|
|
Exit code |
The AWS CLI read |