arktypea
arktype8mo ago
Robb

Discriminated unions with common field but different constraints

Hello,
I am having trouble setting up a schema-system with my types. My code is type-first, so the schemas must be written in accordance to my types.
My entities have a type property, which should be the discriminating property. Two types are possible: typeA and typeB. Both types of entities have a field named someField. By default, someField is nullable, meaning new types in the future should have it nullable. But typeA entities require someField not to be null.
Creating the corresponding schemas lead to a type error when trying to match my types to the schema's types.

Here is my code:
types.ts
interface BaseEntity {
    id: number;
    name: string;
    someField: string | null; // By default, someField can be null
}

interface EntityA extends BaseEntity  {
    type: "typeA";
    someField: string;  // someField cannot be null for typeA
}

interface EntityB extends BaseEntity  {
    type: "typeB";
}


type MyEntity = EntityA | EntityB;

export default MyEntity;


schema.ts
import { type } from "arktype"

const BaseSchema = type({
  name: "string",
  someField: "string | null",
});

const ASchema = BaseSchema.and({
  type: "'typeA'",
  someField: "string",
});

const BSchema = BaseSchema.and({
  type: "'typeB'",
});


export const MySchema = ASchema.or(BSchema);
export type MySchemaType = typeof MySchema.infer;
Was this page helpful?