我想做一个类型来记录数组中对象的属性名称。例如
class C1 {
p1 = 1;
p2 = 2;
static sp1 = 1;
static sp2 = 2;
m1() {
}
m2() {
}
static sm1() {
}
static sm2() {
}
}
type NameOfProperties<T> = ...
type test = NameOfProperties<typeof C1> //=> the result would be ["prototype", "sp1", "sp2", "sm1", "sm2"]
我想客观地了解一下,是否可以这样做?
class C1 {
p1 = 1;
p2 = 2;
static sp1 = 1;
static sp2 = 2;
m1() {}
m2() {}
static sm1() {}
static sm2() {}
}
type NameOfProperties<T> = {
[K in keyof T]: K extends string | number | symbol ? K : never;
}[keyof T];
type Test = NameOfProperties<typeof C1>;
// Result: "p1" | "p2" | "prototype" | "sp1" | "sp2" | "m1" | "m2" | "sm1" | "sm2"
但是请注意: 这包括实例属性、原型属性、静态属性和方法。它不会过滤掉原型属性(如“原型”),并且包含方法名称。