Yannick Schröder
Yannick Schröder

Reputation: 378

Check if variable belongs to custom type in Typescript with same properties

There are the following types:

type TypeA = {
  desc: string;
  name: string;
}

type TypeB = {
  desc: string;
  name: string;
  age: number;
}

type TypeC = {
  desc: string;
  name: string;
  age: number;  
  gender: string;  
}

type TypeAll = TypeA | TypeB | TypeC;

I searched for the solution and I found out that Typeguards are the most elegant way for checking custom types. BUT in all examples they filter for an explicit property of that type. Like:

isTypeC(type: TypeAll):type is TypeC {
  return type.gender !== undefined
}    

How to write that for TypeA or TypeB? Besides it could happen that the Types will be changed over time (not at runtime!) and this needs a solution which is not checking for explicit properties. Is that possible?

Upvotes: 6

Views: 3219

Answers (1)

Marcus Riemer
Marcus Riemer

Reputation: 7688

At runtime all you have is the "raw" JSON-object. Therefore you don't have any other way of asserting its type than checking the payload. Usually one would use some kind of "tagging" property to safely discriminate these different types and avoid any confusion in types with overlapping properties:

type TypeA = {
  type: "A";
  desc: string;
  name: string;
}

type TypeB = {
  type: "B";
  desc: string;
  name: string;
  age: number;
}

type TypeC = {
  type: "B";
  desc: string;
  name: string;
  age: number;  
  gender: string;  
}

type TypeAll = TypeA | TypeB | TypeC;

This design pattern is called "Discriminated Unions", the Typescript Handbook documents the intended usage.

Upvotes: 1

Related Questions