1

I'm taking type-challenge exercise with the easy part, implement the type version of Unshift.(https://github.com/type-challenges/type-challenges/tree/master/questions/3060-easy-unshift) Here is my code:

type Unshift<T extends unknown[], U> = U extends unknown[]
  ? [...U, ...T]
  : [U, ...T]

the problem is with boolean type:

type Res = Unshift<['1', 2, '3'], boolean>
// expected: [boolean,'1',2,'3']
// actual: [false,'1',2,'3'] | [true,'1',2,'3']

I don't know why is that and how to get expected result. BTW, I got a pretty similar solution from another answer(Typescript spread operator for type),

type Cons<H, T extends readonly any[]> =
    ((h: H, ...t: T) => void) extends ((...r: infer R) => void) ? R : never

is it a trick that should be rote?

2
  • 1
    my guess is that this happens because boolean is handled like a union type, if you do something like this type Res = Unshift<['1', 2, '3'], "a" | "b"> you get the same kind of result. EDIT: look at this: tsplay.dev/mZrx9m i think this has to do with the compiler trying to do discriminated unions Commented Mar 25, 2022 at 21:48
  • While an odd presentation, is [false,'1',2,'3'] | [true,'1',2,'3'] different from [boolean,'1',2,'3'] in any meaningful way? Commented Mar 25, 2022 at 22:13

1 Answer 1

2

The reason you get a union result type is that boolean is a union (true | false) and conditional types distribute over union types (docs). Because of this, Unshift<['1', 2, '3'], boolean> evaluates to Unshift<['1', 2, '3'], true> | Unshift<['1', 2, '3'], false>.

You can prevent it from happening by surrounding both sides of the extends condition with square brackets:

type Unshift<T extends unknown[], U> = [U] extends [unknown[]]
  ? [...U, ...T]
  : [U, ...T]

type Res = Unshift<['1', 2, '3'], boolean>
// type Res = [boolean, "1", 2, "3"]

TypeScript playground

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.