Type Narrowing on Discriminated Union in TypeScript

Hello,
I was wondering if there's a clean and simple way to do type narrowing/matching on discriminated union type.

Basically I have something like this:

const FooSchema = Struct({
  identifier: Literal("foo"),
  someProp: String
});

const BarSchema = Struct({
  identifier: Literal("bar"),
  someOtherProp: String
});

const FooOrBar = Union(FooSchema, BarSchema);

const ParentSchema = Struct({
  id: String,
  fooOrBar: FooOrBar
});


Then when doing something like:

const item = arrayOfParents.find((p) => p.foorBar.identifier == "foo")?.foorOrBar


I'd love item to be of type Foo | undefined instead of Foo | Bar | undefined.

Is there a built in way to do that with effect/schema or something else (match for example ?) without having to do type casting or creating my own type guard ?
Was this page helpful?