How to infer recursive container types (with dependent types) in typescript?

Viewed 109

Let's say I can have any of the following values in typescript and I pass it to a function:

[1, [2,3,4], 5]

[1, 2, [3,4,5]]

How can I type the function and the ReturnType of the function so I can preserve all the type information inferred from the values I put in?

I'd like to access the exact same shape out which I put in.

The solution might use a custom (recursive) type, not necessarily tuple/array.

type MyContainerT<???> = ???

let myContainer : () => MyContainerT
let v = myContainer(1, myContainer(2,3,4), 5) // passing in arbitrary, recursive-shaped value
let r = f(v) 
                             
// r SHALL HAVE (INFER) a type like 
// MyContainerT<1, MyContainerT<2,3,4>, 5>, but this is just an idea

function f<???>(v: MyContainerT<???>): MyContainerT<???>{
    // here to access types recursively
    return v // return whatever, but keep EXACT shape
}
0 Answers
Related