Let's say I want my function to a simple Typescript 2-tuple:
type SuperTuple = [number, string]
function torgle(value: string): SuperTuple {
return [value.length, value]
}
This allows me to conveniently destructure the return value of torgle
:
const [index, label] = torgle('pizza')
>> [5, 'pizza']
But I also want to define a special sort of map
function that operates on the first value (number
) only, and passes through the second one:
const hmmm = torgle('pizza').mapIndex(i => i * i)
>> [25, 'pizza']
In Javascript, I can add the mapIndex
function directly, so I can almost make it work like this:
function supTup(num: number, str: string): SuperTuple {
const tup: [number, string] = [num, str]
return Object.assign(tup,
{mapIndex: (f: (x: number) => number) => supTup(f(num), str)}
)
}
function torgle(value: string): SuperTuple {
return supTup(value.length, value)
}
But Typescript is displeased. It might conceivably let me use a generator or class extending Iterator
, but I'm not quite sure what that would look like in this case.
How can I type SuperTuple
and/or torgle
so I can both destructure SuperTuple
as an array and call my custom method on it?
const [string1, label1]: SuperTuple = torgle('pizza')
const [string2, label2]: SuperTuple = torgle('pasta').mapIndex(i => i * 2)