0

I am trying to add a simple generic function to the Array prototype but TypeScript gives me an error about typings that I don't get.

interface Array<T> {
    pluck<T, TKey extends keyof T>(this: T[], key: TKey): T[TKey][];
}

Array.prototype.pluck = function pluck<T, TKey extends keyof T>(this: T[], key: TKey): T[TKey][] {
    return this.map(item => item[key]);
}

Here is a Codesandbox: https://codesandbox.io/s/typescript-playground-export-3oww1?fontsize=14&hidenavigation=1&theme=dark

Thanks for your help :)

3
  • Just omit the typings for your function implementation, you already typed it via the interface declaration Commented Mar 23, 2020 at 9:40
  • Please put the relevant code in this question, so it can be of use to people in the future when they visit here. Commented Mar 23, 2020 at 9:40
  • 3
    Dont do that, just create your new Array which will extend original one. In general you should not override any prototypes, and for sure not the core ones. Commented Mar 23, 2020 at 10:15

1 Answer 1

1

When you refer to a generic parameter in the interface or class definition, you should not create one in the method. Right now TypeScript is correctly pointing out that T coming from Array<T> is not the same as T coming from pluck<T. So if you remove one in the interface definition, everything is fine:

interface Array<T> {
    pluck<TKey extends keyof T>(this: T[], key: TKey): T[TKey][];
}
Sign up to request clarification or add additional context in comments.

Comments

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.