Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save piotrwitek/6e0dae6f9f47b2d91b73deb339692b7e to your computer and use it in GitHub Desktop.
Save piotrwitek/6e0dae6f9f47b2d91b73deb339692b7e to your computer and use it in GitHub Desktop.
Typing a function with an array argument restricted to accept only unique values
// TS v3.4.3
declare function createTest<TAll>(): <
A extends TAll,
B extends Exclude<TAll, A>,
C extends Exclude<TAll, A | B>,
D extends Exclude<TAll, A | B | C>,
E extends Exclude<TAll, A | B | C | D>
>(
arr: [A] | [A, B] | [A, B, C] | [A, B, C, D] | [A, B, C, D, E]
) => void;
type Types = 'A' | 'B' | 'C' | 'D' | 'E';
const test = createTest<Types>();
test(['A']); // OK
test(['A', 'B']); // OK
test(['A', 'A']); // Error
test(['A', 'B', 'C']); // OK
test(['A', 'B', 'A']); // Error
test(['A', 'B', 'C', 'D']); // OK
test(['A', 'B', 'C', 'A']); // Error
test(['A', 'B', 'C', 'D', 'E']); // OK
test(['A', 'B', 'C', 'D', 'A']); // Error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment