#how to remap tuple elements to another type?

24 messages · Page 1 of 1 (latest)

modern bloomBOT
#
andreaelektronvolt#0

Preview:ts type Test = [boolean, string] type Wrap<I> = { value: I wrapped: number } const x: readonly [{[I in Test]: Wrap<I>}] = [ {value: true, wrapped: 2}, {value: "1", wrapped: 2}, ]

gusty saddle
#

@manic hare You can map over arrays with normal mapped types, though I think it needs to be done in a utility type:

type Wrapped<T> = { [K in keyof T]: Wrap<T[K]> };
const x: Wrapped<Test> = [
    { value: true, wrapped: 2}, 
    { value: "1", wrapped: 2}
]
manic hare
#

oh interesting. why only through utility type ?

#

side question is there a way i can enforce a type to be a tuple?

#

expecially with generics. i'd like my generics to be a tuple

#

like class BLA<T> .... make sure T extends tuple

gusty saddle
#

But if the utility type is a mapped type, and you pass it an array, the compiler just maps the values of the array, which is probably what you want.

manic hare
#

Yeah strange it doesn't od that without utility type as well

#

Thanks for the heads-up

gusty saddle
#

I think the difference is that when you do Wrapped<Test> it's able to look at Wrapped and see that it's a mapped type, but if you do it inline, it would have to do some higher-level analysis to understand that [K in keyof Test] shouldn't literally do what it says but should do something else.

#

And, no I don't think there's any way to restrict only allowing tuples, generically.

#

Though you can use const to make it more likely:

function preferTuple<const T extends readonly unknown[]>(tuple: T) { return tuple; }

preferTuple([1,2,3]); // readonly [1,2,3]
royal mist
#

T extends readonly unknown[] is making sure that T extends tuple. But mutable arrays extend tuples. If you use T as a function argument you can enforce that it must be readonly at that point - works best if it a constructor argument constructor(t: Tuple<T>)
type Tuple<T extends readonly unknown[]> = T extends unknown[] ? 'T must be a tuple' : T

gusty saddle
#

readonly unknown[] is not necessarily a tuple, just a read-only array.

royal mist
#

What is the difference?

#

Hmm right a tuple can writable

#

I guess you can just do

#

T extends [unknown]

gusty saddle
#

That would only allow for single element tuples.

royal mist
#

Oh yeah because of the length prop

#

T extends [unknown, ...unknown[]]

#

Third time lucky?

gusty saddle
#

Technically that excludes an empty tuple since it's requiring a minimum length of one, but might be fine depending on what the goal of "only allow tuples" is.