如何获取具有静态成员的类的值类型



假设我有一个类似的类

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

如何将静态类的值作为一种类型进行访问,以使结果是这样的。

type ValueOfStaticClassMember = 1 | 2;

您可以通过typeof StaticClass获取StaticClass对象本身的类型。然后,您的任务是删除prototype属性和(我猜(任何静态方法,这样我们就只剩下静态属性了。您可以使用映射类型来实现这一点,在映射类型中,您可以将键prototype和任何引用函数的键映射到never(因此它不会显示在结果类型中(,如下所示:

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

游乐场链接

如果do想要包含静态方法,只需从密钥中删除第二个条件:

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)

游乐场链接

最新更新