是否可以将对象的属性名称映射为数组?

问题描述 投票:0回答:1

我想做一个类型来记录对象的属性名称(如果我传递静态引用,应该只返回静态属性)作为数组。例如

class C1 {

    p1 = 1;

    p2 = 2;

    static sp1 = 1;

    static sp2 = 2;

    m1() {

    }

    m2() {

    }

    static sm1() {

    }

    static sm2(): "hello" {
        return "hello";
    }

}


type NameOfProperties<T> = ...

type test = NameOfProperties<C1> //=> the result should be ["p1", "p2", "m1", "m2"]

type staticTest = NameOfProperties<typeof C1> //=> the result should be ["prototype", "sp1", "sp2", "sm1", "sm2"]

我想客观地了解一下,是否可以这样做?

typescript
1个回答
0
投票
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"

但是请注意: 这包括实例属性、原型属性、静态属性和方法。它不会过滤掉原型属性(如“原型”),并且包含方法名称。

© www.soinside.com 2019 - 2024. All rights reserved.