#Intersection across multiple types/keys

7 messages · Page 1 of 1 (latest)

radiant kettle
#

Is there any way to the get the final availableAndPrimary object in this Playground to require both the availableDate and primaryKey keys using the All type?

I've tried various combinations of Unions/Intersections to solve this, but none have worked for every case.

silk ospreyBOT
#
andjsrk#0

Preview:```ts
type Status = "Available" | "Unavailable" | "Other"
type Type = "Primary" | "Secondary" | "Tertiary"

type Base = {
name: string
status: Exclude<Status, "Available"> // Since Available has its own 'type'
type: Exclude<Type, "Primary"> // Since Type has its own 'type
...```

outer tinsel
#

the point is that making the union "exclusive" so they cannot overlap at all

#

so i Exclude-ed some cases like in Base

grave mantle
#

Personally here's how I'd approach it:

// Common fields, not part of any union
type Base = { name: string; }

// Status field and fields controlled by it
type StatusUnion = {
  status: "Available",
  availableDate: string;
} | { status: "Unavailable" | "Other"}

// Type field and fields controlled by it
type TypeUnion = {
  type: "Primary",
  primaryKey: string
} | { type: "Secondary" | "Tertiary" }

type All = Base & StatusUnion & TypeUnion;

type Status = All["status"];
type Type = All["type"];
silk ospreyBOT
grave mantle
#

This makes a discriminated union for each part of the object that's controlled by a particular property, and then intersects them together.