What is the best TypeScript Approach for Relational Collections using SDK?

Hi everyone,

I’m using the Directus SDK with TypeScript, and I’m trying to figure out the best way to handle typing for relational collections.

For example, I have two collections: products and variants, where each product has one or more variants.

Here’s a simplified version of my types:

interface Variant = {
  id: number;
  name: string;
  price: number;
};

interface Product = {
  id: number;
  name: string;
  variants: number[] | Variant[];
};

interface Schema = {
  products: Product[];
  variants: Variant[];
};

I create the client like this:

const directus = createDirectus<Schema>('http://directus.example.com').with(rest());

What’s the best way to handle this from a typing perspective?

What I’d like to do is write two readItems functions for products:

  • One that returns products with just the variant IDs
  • Another that returns products with full Variant objects populated

I’ve seen a bunch of possible ways to handle this, but I’d really like to know how someone with more experience would approach it

Great question. And welcome to the community :waving_hand:

Here’s a standard format that we recommend in the docs.

import { createDirectus, rest } from '@directus/sdk';

interface Post {
  id: number;
  title: string;
  content: string;
}

interface Schema {
  posts: Post[];
}

const directus = createDirectus<Schema>('http://directus.example.com').with(rest());

We currently don’t have an official types generator but no worries.

There are several community extensions that you can add to your instance through the marketplace or npm.

Or you can use this package that I created for our starter templates to automate the type generation process.