How do you define function arguments with the rest operator to be an array of keys defined in a given type? I also need the return object to be an object shaped by the given argument keys & their corresponding types from the T
type.
type MyType<T> = {
...,
// This is my struggle function
myCallableFunction(...keys: keyof T[]) => object
}
The answer I was looking for ended up using Pick
:
type MyType<T> = {
myFunctionCall<U extends keyof T>(...keys: U[]): Pick<T, U>;
};
The object that myFunctionCall
returns will have the listed properties from T
with their value types as defined on T
. So if T
has the properties a
and b
of type number
and c
and d
of type string
, then the return type of theObject.myFunction("a", "c")
will be Pick<T, "a" | "c">
Pick<T, "a" | "c">
, which is {a: number; c: string;}
{a: number; c: string;}
(in that example).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.