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}, ]
#how to remap tuple elements to another type?
24 messages · Page 1 of 1 (latest)
@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}
]
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
I think it may just be a special case that the compiler handles - the issue is that if you just plug in Test for T you do keyof Test and you get stuff like "length" | "concat", etc.
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.
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]
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
readonly unknown[] is not necessarily a tuple, just a read-only array.
What is the difference?
Hmm right a tuple can writable
I guess you can just do
T extends [unknown]
That would only allow for single element tuples.
Oh yeah because of the length prop
T extends [unknown, ...unknown[]]
Third time lucky?
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.