In typescript it's possbile to declare a function that expects a type and one of its keys as parameters:
function foo<T, K extends keyof T>(object: T, key: K)
In the function body you're then able to get or set the value of the object
's key value and even extract the type of the key (T[k]
):
function setter<T, K extends keyof T>(object: T, key: K){
return (value: T[K]) => {
obj[key] = value;
};
}
function logger<T, K extends keyof T>(object: T, key: K){
console.log(obj[key]);
}
Question:
Is it possbile to have generic type K
that extends keyof T
and is an array?
(In other words: K
must be an array and a key of type T
)
Example use case:
function lengthLogger<T, K /*extends keyof T and is array*/>(object: T, key: K){
console.log(object[key].length)
}