DEV Community

Dmitri Pisarev 🇷🇺
Dmitri Pisarev 🇷🇺

Posted on

Annoying TypeScript discriminating union gotcha

Can you spot what's wrong with this code?

Discriminating union gone wrong

https://www.typescriptlang.org/play?ts=4.2.3#code/C4TwDgpgBACgTgezAZygXigbwFBT1AS2QEE44BDEALigDNyAbZCAGl31oDsaAKAN0YBXCDWTA4BTgHMAlOgB8UPggIATbAF8oAHyzs8RUhWpRxwtvjrco-ISKhiJ0gNoBdOWkXK1m7NgDGCJxiUADCCAC2YEEQnMDoNpiGZJQsVho08EjIHoo4loHB8f6MDABG5P4A1gk8uXqWlgS0NsnGcvmNXVw8zgDk5MiqtKp97vqNWhBM0J1dlj19AIwATADMfTITlhoTuxpAA

Top comments (2)

Collapse
 
sevaru profile image
sevaru

TLTR It would work if you write like this

const Component = (props: Props) => {
    const callback = () => {
        if (props.isArray) {
            props.fn(['asdfd'])
        } else {
            props.fn('123')
        }
    }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
dimaip profile image
Dmitri Pisarev 🇷🇺

Yup, exactly! During restructuring TypeScript looses relation between object members.