Home > Net >  How to get the value type for class with static members
How to get the value type for class with static members

Time:10-05

Let's say I have a class like this

class StaticClass {
  static readonly HELLO = 1
  static readonly WORLD = 2
}

How can i access the values of the static class as a type such that the result would be as such.

type ValueOfStaticClassMember = 1 | 2;

CodePudding user response:

You can get the type of the StaticClass object itself via typeof StaticClass. Then your task is to remove the prototype property and (I'm guessing) any static methods so we're left only with static properties. You can do that with a mapped type where you map the key prototype and any key referring to a function to never (so it doesn't show up in the resulting type), like this:

class StaticClass {
    static readonly HELLO = 1
    static readonly WORLD = 2
    static method() {} // Added this just to ensure it didn't come through
}

type ClassStaticProperties<T> = {
    [Key in keyof T as Key extends "prototype" ? never : T[Key] extends (...args: any[]) => any ? never : Key]: T[Key];
}

type StaticProperties = ClassStaticProperties<typeof StaticClass>;
//   ^? type StaticProperties = { readonly HELLO: 1; readonly WORLD: 2; }
type ValueOfStaticClassMember = StaticProperties[keyof StaticProperties];
//   ^? type ValueOfStaticClassmember = 1 | 2

Playground link

If you do want to include static methods, just remove the second conditional from the key:

type ClassStaticMembers<T> = {
    [Key in keyof T as Key extends "prototype" ? never : Key]: T[Key];
}
type StaticMembers = ClassStaticMembers<typeof StaticClass>;
//   ^? type StaticMembers = { readonly HELLO: 1; readonly WORLD: 2; method: () => void; }
type ValueOfStaticClassMember = StaticMembers[keyof StaticMembers];
//   ^? type ValueOfStaticClassMember = 1 | 2 | (() => void)

Playground link

  • Related