Home > Net >  Internal class type in typescript
Internal class type in typescript

Time:12-09

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:

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 ?

CodePudding user response:

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

  • Related