1

Similar to this example

type Arr = [true, false, "string"]

type t = Arr[0] // true

Id like to assign the types of a sprad operators parameters.

// Not correct syntax; Just thought as an example
function func(...param: [...Arr]) {}

So that the function could be called like this

func(true, false, "string")

Of course for this simple example you could just explicitly tell the function its parameters. Though I need this in order to be able to wrap those types each into an object as generic, without knowing them.

class Data<Type> {

}

class Cls<Types extends any[]> {
  constructor(...data: Data<Types[{{{at index of spread operator}}}]>)
}

If this is not possible, a solution based on infering the Types out of the generics would also be appreciated.

1 Answer 1

1

You don't need to spread the tuple type, the spread is needed just on the parameter:

type Arr = [true, false, "string"]

function func(...param: Arr) { }
func(true, false, "string")
func(true, false, "stringg") // err

Playground Link

See PR for the whole picture.

To the second part of your question, to warp each tuple member in another generic type, you could use a mapped type:


type Promisify<T> = { 
    [P in keyof T]: Promise<T[P]>
}


function func2(...param: Promisify<Arr>) { }
// Same as 
// func2(param_0: Promise<true>, param_1: Promise<false>, param_2: Promise<"string">): void

Playground Link

Sign up to request clarification or add additional context in comments.

4 Comments

But how would I wrap each tuple value into a other type as a generic?
@zzrv edited the answer, you just need to use a mapped type
Thanks alot, ill try this asap
Your promisify solution workes well for simple cases, though as demonstrated here tinyurl.com/[[[v6429o2]]] it doesnt cope very well with more complex types. I really need to type information in the more first (not working example). Do you have any ideas of how to make this work, or is this an issue with typescript?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.