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.

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay