sindresorhus / type-fest

A collection of essential TypeScript types
Creative Commons Zero v1.0 Universal
14.13k stars 533 forks source link

`LiteralList<Union>` #904

Open macmillen opened 3 months ago

macmillen commented 3 months ago

I want to be able to define an array that contains exactly the elements of all possible values of a union once.

type Union = "prevStep" | "nextStep" | "submit" | "order";

// this works:
const list: LiteralList<Union> = ["nextStep", "order", "prevStep", "submit"];

// this fails:
const list: LiteralList<Union> = ["nextStep", "order", "prevStep", "submit", "submit"];

// this fails:
const list: LiteralList<Union> = ["nextStep", "order", "prevStep"];

I already made this work with this type:

type LiteralList<T extends string, U = T> = [T] extends [never]
  ? []
  : U extends T
  ? [U, ...LiteralList<Exclude<T, U>>]
  : [];

I'm not sure though if it makes sense since I asked ChatGPT to do it.

Is it possible to add this type helper to type-fest?

Upvote & Fund

Fund with Polar

macmillen commented 3 months ago

I realized that this:

type LiteralList<T extends string, U = T> = [T] extends [never]
  ? []
  : U extends T
  ? [U, ...LiteralList<Exclude<T, U>>]
  : [];

for some reason is really slowing down the TS language server.

Is there maybe another way to achieve this?

Emiyaaaaa commented 3 months ago

Related to https://github.com/sindresorhus/type-fest/pull/686