#Is it possible to type a generic array of tuple with each row its own type ?

19 messages · Page 1 of 1 (latest)

solemn heart
#

Hello !
I am quite new using typescript and I need some help on typing the following code :

I would like to have an array of tuples with 2 functions, the first function is a typeguard and the second function has a parameter with the same type of the typeguard assertion. The idea is to have an array of tuples like a switch which will execute the function when the typeguard is matching and highlight the tuples not matching this rule.

Here is the type I have defined for a single tuple.

type WhenThen<T,V extends T> = [(a: T ) => a is V , (b: V) => string]

Is it even possible ?

Thank you very much !

grim halo
#

You can do it with validator pattern, not sure if that’s worth it though.

#

And I don’t think there’s a point in splitting up when and then?

solemn heart
#

Thanks you very much for the answer. I was thinking about splitting the code in order to avoid code redundancy when we want to apply the same function on 2 different types for instance.

#

What is exactly the validator pattern ?

grim halo
#

You can reuse code within the arrow function though

shadow flareBOT
#
nonspicyburrito#0

Preview:```ts
function transform<T>(
input: T,
...transformers: ((input: T) => false | string)[]
) {
for (const transformer of transformers) {
const result = transformer(input)
if (result !== false) return result
}

return undefined
}
...```

grim halo
#

As for validator pattern, it's a way to check and verify an argument's type with arbitrary type logic.

shadow flareBOT
#
nonspicyburrito#0

Preview:```ts
type ValidateTransformers<T, U> = {
[K in keyof U]: U[K] extends [
when: (input: T) => input is infer R extends T,
then: (input: infer I) => string,
]
? R extends I
? U[K]
: never
: never
}

function transform<
...```

grim halo
#

Here's how you do it with validator pattern, but honestly, it's really bad.

solemn heart
#

Woaw, very nice

#

Thank you, I need to take time and look at the code closer 😁

#

but that's exactly what I tried to do since yesterday

#

Gracias Burrito

icy bloom
shadow flareBOT
#
k.a.m.n#0

Preview:```ts
class MyClass<T extends any[]> {
public run(arg: T): void {}
}

class MySubclass<T extends any[]> extends MyClass<T> {}

type MyClassTuple<T extends any[]> = {
[K in keyof T]: T[K] extends MyClass<any>
? T[K]
: unknown
}

function takeTuples<T extends any[]>(
arg: T
): MyClassTuple<T>
...```

icy bloom
#

Apparently, the result var in the playground is typed as unknow[]. Is there anyway I can make some more specific type?

grim halo
#

It doesn't seem like this relates to the original question, you should open your own help thread rather than hijacking someone else's.