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

Internal class type in typescript

Is there a way to create internal class types in typescript ? Something like this:

class Example<Data extends Record<string, any>> {
  type Key = keyof Data; // not allowed
  getKeys(): Key[] { ... }
}

This is possible within function blocks, for instance:

function getKeys<Data extends Record<string, any>>(data: Data) {
  type Key = keyof Data; // allowed
  const keys: Key[] = Object.keys(data);
  return keys
}

The closest solution is to define a generic:

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

class Example<Data extends Record<string, any>, Key = keyof Data> {
  getKeys(): Key[] { return [] }
}

const example = new Example<{aKey: 'value'}>();

const example2 = new Example<{aKey: 'value'}, "aKey">();

But :

  • The type key could be overridden (because we only give a default value to T)
  • Because it can be overridden, in a few case TS will complain if I assume the returned type to be T while not explicitly casting it.

Any clean solution or workaround ?

>Solution :

AFAIK this is currently not possible: see #7061: Permit type alias declarations inside a class

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