![]() ) but we can represent it as a generic constraint that we pass to a helper function. It can't be done as a concrete type (so no const a: UniqueArray =. The following isn't perfect, but it produces error messages that are possibly reasonable if you squint: type Invalid = Error & The idea is a type to which no value can be assigned (like never) but which produces a custom error message when the compiler encounters it. Here's how I might do it:įirst we come up something that acts like an invalid type, which TypeScript doesn't have. ![]() say, from a developer using your code as a library, then you have a chance of getting something that works, but it's complex and possibly brittle. If you're getting tuples of literals (possibly via const assertion). So if you're passing arrays you get from other functions, or from an API, etc., and the type of these arrays is something like number, then the answer is just "no, you can't do this". In all the other cases, the compiler doesn't understand what's going on. the compiler would realize that tupleOfLiterals has exactly 3 elements, two of which are the same type. Only the first one would behave as you'd like. For example, here are some arrays with the same runtime values, but with different types in TypeScript: const tupleOfLiterals: = Ĭonst tupleOfNonLiterals: = Ĭonst arrayOfLiterals: (1 | 2) = Ĭonst arrayOfNonLiterals: number = Ĭonst constAssertedReadOnlyTupleOfLiterals = as const The only possible way this could work at compile time is if your arrays are tuples composed of literals. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |