Consider the following working function:
function props<
T extends any,
P extends keyof T,
V extends T[P]
>(t:T,p:P,v:V){
//...
}
props([],"length",1)
props([],"lengt",1) // error
props([],"length","1") // error
How could I write this to accept a collection of tuples, e.g.
props(
[[],"length",1],
[[],"length",10],
[[],"length","1"] // error
)
Without resorting to a passthrough function like so:
multiProps(
props([],"length",1),
props([],"lengt",1),
props([],"length","1")
)
So far I've been able to write a function that accepts tuples of the form [object,"prop"]
but have been unable to have it accept tuples with the third item (the value).
Partial solution:
function props<A extends any[]>
(...tuples:[...{
[K in keyof A]:[
A[K],
keyof A[K],
// ???
]
}]
){
//...
}
props(
[[],"length"],
[{a:1},"a"],
[{b:2},"a"] // error.
)
CodePudding user response:
You can use an array type to represent the list of the type parameters
function props<
T extends any[],
P extends {[k in keyof T]: keyof T[k]},
V extends {[k in keyof T]: T[k][P[k]]}
>(...args: {[k in keyof T]: [t:T[k],p:P[k],v:V[k]]}){
//...
}
props(
[[],"length", 0],
[{a:1},"a", 1],
[{b:2},"a", 3] // error.
)