I haven't come across a question similar to this one before. My goal is to develop a type guard that can accurately determine the type of a specific variable. It's quite simple with a single type.
type A = { id: number, title: string, type: string };
type B = { id: number, title: string, type: string };
type ABUnion = A | B;
const isA = (value: ABUnion): value is A => value.type === 'A';
However, in certain scenarios, I encounter these types encapsulated within another type and aim to preserve the wrapper type while ensuring that the inner type matches my requirement.
type A = { id: number, title: string, type: string };
type B = { id: number, title: string, type: string };
type ABUnion = A | B | Readonly<A> | Readonly<B>;
const isA = (value: ABUnion): value is A => value.type === 'A';
In this situation, regardless of passing a Readonly<A>
into the guard, I consistently receive a typeof A, which is as anticipated.
How can I modify isA
to output either A
or Readonly<A>
(or a different wrapped type)?