Skip to content
On this page

generateIdentifierType ‚Äč

typescript
generateIdentifierType: (
  column: TableColumn,
  details: TableDetails,
  config: InstantiatedConfig
) => TypeDeclaration;

This function is called for table columns that are marked as primary keys. It can be used to create specific types for such properties.

The default implementation creates a branded type which is a Typescript trick for creating nominal types. With these, you can be certain that you don't accidentally end up assigning a MemberId to an AccountId, even if those are both represented as integers in the database.

It looks like this:

ts
export const defaultGenerateIdentifierType: GenerateIdentifierType = (
  column,
  details,
  config
) => {
  const name = toPascalCase(details.name) + toPascalCase(column.name);
  const innerType = resolveType(column, details, {
    ...config,
    // Explicitly disable identifier resolution so we get the actual inner type here
    generateIdentifierType: undefined,
  });
  const imports = [];

  let type = innerType;
  if (typeof innerType === 'object') {
    // Handle non-primitives
    type = innerType.name;
    imports.push(innerType);
  }

  return {
    declarationType: 'typeDeclaration',
    name,
    exportAs: 'named',
    typeDefinition: [`${type} & { __brand: '${name}' }`],
    typeImports: imports,
    comment: [`Identifier type for ${details.schemaName}.${details.name}`],
  };
};