Kruton
Kruton

Reputation: 43

Why is Action<"test", boolean> spread into union of Action<"test", true> | Action<"test", false>

The definition of Action is

    type Action<T = string, P = any> = { p: P }["p"] extends undefined
        ? { type: T; payload?: P }
        : { type: T; payload: P };

But even though I have wrapped the checking of payload in object, it is still getting spreaded into union:

type Actions =  Action<"runTest", boolean>

resolves to

enter image description here

I don't want it to get spreaded. How do I keep the type of payload to be boolean?

Upvotes: 2

Views: 36

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249726

The problem is that { p: P }["p"] resolves P which is a naked type parameter. Conditional types distribute over naked type parameters, as you can read about in the docs.

You can disable distribution by wrapping the type parameter in a tuple type:

type Action<T = string, P = any> = [P] extends [undefined]
        ? { type: T; payload?: P }
        : { type: T; payload: P };


type Actions =  Action<"runTest", boolean>

Playground Link

Upvotes: 2

Related Questions