The TypeScript documentation mentions a pick function that is declared but not implemented. In an attempt to create a simplified version, I wrote the following:
function pick<T, K extends keyof T>(obj: T, key: K): Pick<T, K> {
return { [key]: obj[key] }
}
When testing this implementation, I encountered the error message: "TS2322: Type { [x: string]: T[K]; }
is not assignable to type Pick
." The issue seems to be related to key
being generalized as string
instead of keyof T
. Is it possible to implement pick
without resorting to using any
or explicit casting like as Pick<T, K>
? Additionally, I want to emphasize that I do not wish to utilize Partial<T>
as a return type, but rather return a specific field chosen by the user.
As an alternative approach, I also attempted the following:
function pick<T, K extends keyof T>(obj: T, key: K): { [key in K]: T[K] } {
return { [key]: obj[key] }
}
Unfortunately, this resulted in a similar error. My current TypeScript version is 4.7.4
.