top | item 41123988

(no title)

noway421 | 1 year ago

Here's a simpler repro:

    type Bird = { id: number };
    type Human = { swim?: () => void; id: number };

    function move(animal: Bird | Human) {
        onlyForHumans(animal); 
    }

    function onlyForHumans(swimmer: Human) {
      if (swimmer.swim) {
        swimmer.swim();
      }
    }

    const someObj = { id: 1, swim: "not-callable" };
    move(someObj);
`someObj` gets casted as `Bird`, then `animal` gets casted as `Human`. Unfortunately unions here are indeed unsound.

As as workaround you could add a property `type` (either `"bird"` or `"human"`) to both `Bird` and `Human`, then TypeScript would be able to catch it.

discuss

order

No comments yet.