// Table.schema just validates the type of the definition
const UserSchema = Table.schema({
columns: {
id: 'text',
dob: 'date',
friends: { type: 'map', keyType: 'text', valueType: 'uuid' },
},
primaryKey: {
partitionBy: ['id'],
partitionSort: { dob: -1 }
},
});
// equivalent to:
// type User = {
// id: string,
// dob: DataAPIDate,
// friends?: Map<string, UUID>, (optional since it's not in the primary key)
// }
type User = InferTableSchema<typeof UserSchema>;
// equivalent to:
// type UserPK = Pick<User, 'id' | 'dob'>;
type UserPK = InferTablePrimaryKey<typeof mkTable>;
// table :: Table<User, UserPK>
const table = await db.createTable<User, UserPK>('users', {
definition: UserSchema,
ifNotExists: true,
});
You can also infer the schema from a Table instance directly, if necessary.
This type provides flexible ways to infer a table’s schema—whether from a Table instance directly, a Promise
resolving to a Table
, or a function returning either of those.
// ESM users can use top-level _await_ to create the table instance
// and the type may be declared globally without issue
const table = await db.createTable('users', {
definition: {
columns: ...,
primaryKey: ...,
}
});
type User = InferTableSchema<typeof table>;
type UserPK = InferTablePrimaryKey<typeof table>;
// CJS users may not be able to use top-level _await_ to create the table instance
// but may instead create a utility function to create the table instance
// and use the type of that function to infer the table's type globally
const mkUsersTable = async () => await db.createTable('users', {
definition: ...,
});
type User = InferTableSchema<typeof mkUsersTable>;
type UserPK = InferTablePrimaryKey<typeof mkUsersTable>;
async function main() {
const table = await mkUsersTable();
}
Overview
Enumerates the possible source types from which a Table's TypeScript type can be inferred using InferTableSchema-like utility types.
This means that there are multiple ways to infer a table's schema, and the type system will automatically pick the right one based on the context in which it is used.
✨Inferring from a CreateTableDefinition (recommended)
The recommended way to infer the TS-type of the table is by using the Table.schema method to create a CreateTableDefinition object, and then using the InferTableSchema-like utility types to infer the TS-type from that object.
This is recommended over the below inferring methods because this method: