soydev
soydev
TTCTheo's Typesafe Cult
Created by soydev on 12/10/2023 in #questions
Problem with TS conditional on union
I'm currently playing around with typescript conditionals, and doing conditionals on string literal unions isn't quite working for me
type EventsType = 'ready' | 'data' | 'reset' | 'end'

type Discriminate<T extends EventsType> = T extends 'reset' | 'end'
? () => void
: dosomth<T>

type dosomth<T extends 'data' | 'ready'> = (data: string, type: T) => void
type EventsType = 'ready' | 'data' | 'reset' | 'end'

type Discriminate<T extends EventsType> = T extends 'reset' | 'end'
? () => void
: dosomth<T>

type dosomth<T extends 'data' | 'ready'> = (data: string, type: T) => void
This is the code that i have, but for some reason, TS is complaining that
typescript: Type 'T' does not satisfy the constraint '"data" | "ready"'.
Type 'EventsType' is not assignable to type '"data" | "ready"'.
Type '"reset"' is not assignable to type '"data" | "ready"'. [2344]
typescript: Type 'T' does not satisfy the constraint '"data" | "ready"'.
Type 'EventsType' is not assignable to type '"data" | "ready"'.
Type '"reset"' is not assignable to type '"data" | "ready"'. [2344]
in the dosmth<T> line https://www.typescriptlang.org/play?#code/C4TwDgpgBAogbhAdsAzgFXNAvFA5AJwgEMATEXKAHzxKOCIuoIhQmEbyRNwCgfRIUACIBLFAGN8IgLYjEdCAB40UCAA9gXFLATJ0mAHxQcK9ZsQltzVuyqcLvKFAD8UABQBKY0bgB7ESQ8TgBcUCS+KL7SwAAWygZ8AtDhkdFxphpaNHQMdsyk5EY4brT0oSjAUogA5gA0UEmhaF5YPv6BPEA here is the typescript playground. What am i doing wrong? Why isn't it correctly taking the 'reset' string literal out of T?
6 replies
TTCTheo's Typesafe Cult
Created by soydev on 9/19/2022 in #questions
Typescript behaving strangely when inferring function return type
4 replies
TTCTheo's Typesafe Cult
Created by soydev on 9/18/2022 in #questions
Route guards for searchparams in nextjs
Is there any good way of parsing searchparams, asserting them to a schema and rewriting/redirecting the request to a url with corrected searchparams while maintaining full typesafety? I've written some code in the middleware, but I have zero typesafety regarding the search params in the pages and need to manually assign the types. Is there a good way to declare what kind of params a page takes?
1 replies