juanm04
Explore posts from serversTTCTheo's Typesafe Cult
•Created by juanm04 on 6/27/2023 in #questions
Type-guards and generics
I have a (quite) specific question about type-guards. I want to define some variable, and I want that variable type to depend on a constant. For instance, I have a constant
size: 8 | 16
(which comes as an argument to a function), and I want my variable byte: [Byte<8> if size = 8 or Byte<16> if size = 16]
. My first instinct was to declare byte: Byte<typeof size>
. This doesn't work as expected. I've made this quick playground to illustrate my problem: https://www.typescriptlang.org/play?#code/C4TwDgpgBAQiwQDwBUDKBLAXtCAPBAdgCYDOUAHFAD5QCMAbAHxQC8UaWO+ExZlA-FADaBAK4BbAEYQATgF0oALmFipsgDRRV0+QG4AUPtCRY8CJTZwEicowNQHUAPROoAPX6Hj0KxAatTawY7fUdnVw9DADNRAgBjYHQAewIoEiTxCGAAC3QCAHMAChJOZUoaBgBKKABvUMcAGyyoSTNlX0RvJKi0zhCw9B7izlYWNnJqurCw1oR7aYcXd08FhybgKAQSYF92s07wCG7e7H7VsKXIsIBffWugA
Maybe the Byte<typeof size>
approach is incorrect. Is there a nice way to fix this?2 replies