Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typesafely extending Object prototype in TS


const via = Symbol('via')

declare global {

  interface Object {
    [via]<R>(cont:(self:this)=>R):R
  }
}

const test = [1,2,3][via](x=>x) // test is inferred as Object, it should be inferred as number[]

Is there a way to type annotate this correctly?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Use a generic parameter in the interface that TypeScript correctly infers the type of the caller and applies it to the function argument and return type:

const via = Symbol('via');

declare global {
  interface Object {
    [via]<R, T = this>(this: T, cont: (self: T) => R): R;
  }
}

Object.prototype[via] = function<R, T = this>(this: T, cont: (self: T) => R): R {
  return cont(this);
};

const test = [1, 2, 3][via](x => x);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading