Last active
May 28, 2025 13:30
-
-
Save loucadufault/a2287b8e85c7059ebdb45f910e153876 to your computer and use it in GitHub Desktop.
TypeScript pattern for enforcing that a tuple have the exact same items as the members of a union (one-liner, avoids linter errors)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import type { IsEqual, TupleToUnion } from 'type-fest' | |
| type IsTupleEqual<TTuple, TExpected> = IsEqual<TupleToUnion<TTuple>, TExpected> | |
| // --- | |
| type ExpectedItem = 'a' | 'b' | 'c' | |
| const myArr = ['b', 'c', 'a'] as const | |
| true satisfies IsTupleEqual<typeof myArr, ExpectedItem> // ts error if myArr has any fewer or excess items |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://www.typescriptlang.org/play/?#code/JYWwDg9gTgLgBDAnmApnA3nAkgZwKICOArgIYA2ANHACpFhkrUQCqAdsBK1Wx607fTQBfOADMoEEHADkSVAFpRKHDGkAoNXLS4BDQqTIAearpRVqeAB6oAxjBQATAHxwAvNnzFyxugyY9OY1Mncytbe2cNAHoouHl4jS04MJQ7Ryx7KXdpEmk4AB8ZACM8wukbdTUYuBQvMjgQFBAilCgcOCKieAguuAhRPqgHVo0bThUGxABBKCg3OABtaRKqculV3IBdOBJ2sdYVRKgiNBwSGGAcUWBlD1N9by1+yZmoKhS0hwyml2qYdtaEjmwAGMF8aAAFrsdqxEA1LjhgKwAOaDGqWGzKdrATI4aKxM6NdEkcAMKhEREohDIFCKZSqdoBPgQUwALjgEJgMDAOFZMWROIhRCKADoxiAopSHFBlNAhTgolo6SookUyBAilEQCQkZKelBMVEiOxOPIYBAzeCRQ4Rf9RuN4CBprMAEzspn8cGGD4Rb4gFzuJYrGQVDbSbbQ-YTP4A2bQOAghDgjnQ2oGBpNFptDq9HrdAbQYZQNRRx3OqAAZndJuZpm91lSvsyAcWOXWxXbawjewd+PhOEpqMazRGJYdkwAQiQHK95ktcqsSt24KWjic4GcLlcbu0dOCHkYngMnVOZ7N3g3Pn6nH2UBisRmR8Wxwcy6fXi6523F53QzIHOGOw9q+a6nOclzXLce6CAehhHpO04fhe4TpM2ahAA