San Jay Falcon
San Jay Falcon

Reputation: 1013

Casting output of BehaviourSubject to a different Type

Lets say we have:

private userSource = new BehaviorSubject<UserType1 | UserType2>({});

Eventually returns a UserType3 or maybe dynamic Type, which can be a specific Type but to be agreed upon during the process.

Is it possible to cast the return Type of a BehaviourSubject to different Type?

Upvotes: 0

Views: 88

Answers (1)

Andrei Gătej
Andrei Gătej

Reputation: 11934

The first thing that comes in mind is using Discriminated Unions.

The main idea is that you'll have a union of types and all these types will have a common singleton type.

In short, this is what it will allow you to do:


interface UserTypeOne {
  type?: 't1';
  name: string;
  age:  number;
}

interface UserTypeTwo {
  type?: 't2'
  address: {
    street: string
  }
  city: string;
}

interface UserTypeThree {
  type?: 't3';
  hobbies: string[];
}

/* ... */

type Users = UserTypeOne | UserTypeTwo | UserTypeThree;

/* ... */

const userSource$ = new BehaviorSubject<Users>(null);

/* ... */

switch (u.type) {
      case "t1": {
        console.log('type1', u.age, u.name)

        return;
      }

      case "t2": {
        console.log('type2', u.city, u.address.street)

        return;
      }

      case "t3": {
        console.log('type3', u.hobbies)

        return;
      }      
    }

Here is a StackBlitz demo.

Upvotes: 2

Related Questions