jack miao
jack miao

Reputation: 1498

Fail to use switch statement based on typeof object

in my html im using a function to call getObjInfo(oBJ) And im passing it the object. now I have switch statement in my getObjInfo func to return something base on the type of the obj that got passed by the html, it looks like this (Cars , People , Animals are interfaces):

public getObjInfo(elem: Cars | People | Animals) {
    switch (typeof(elem)) {
      case 'Cars':
        return elem.color;
      case 'People':
        return elem.age;
      case 'Animals':
        return elem.name;
    }
  }

this is the html that passes it:

  <div class="list-bg" *ngFor="#obj of listToDisplay">
    {{getObjInfo(obj)}}
  </div>

i dont get any errors, its just dosent work...what am i doing wrong..?

Upvotes: 2

Views: 255

Answers (1)

Nitzan Tomer
Nitzan Tomer

Reputation: 164307

If Cars, People and Animals are interfaces then you cannot do it with typeof as these interfaces only exist at compilation time and are absent in runtime.

You can have a function that checks the properties of the elem and returns the type:

function getElementType(elem: Cars | People | Animals) {
    if (elem.carProperty1 && elem.carProperty2) {
        return "Cars";
    }

    if (elem.peopleProperty1 && elem.peopleProperty2) {
        return "People";
    }

    if (elem.animalsProperty1 && elem.animalsProperty2) {
        return "Animals";
    }

    return "unknown"
}

And then:

public getObjInfo(elem: Cars | People | Animals) {
    switch (getElementType(elem)) {
        case 'Cars':
            return elem.color;
        case 'People':
            return elem.age;
        case 'Animals':
            return elem.name;
    }
}

However, if you turn those interfaces into classes you'll be able to do that using instanceof.

Upvotes: 4

Related Questions