获取typescript类的所有属性,即使它们是隐式未定义的
我目前正在尝试动态获取一个具有类的属性名的数组。然而,似乎只有显式地获得未定义的属性和具有值的属性是可能的 以下是一个例子:获取typescript类的所有属性,即使它们是隐式未定义的,typescript,class,properties,Typescript,Class,Properties,我目前正在尝试动态获取一个具有类的属性名的数组。然而,似乎只有显式地获得未定义的属性和具有值的属性是可能的 以下是一个例子: class foo { prop1: string; prop2: number; prop1ExplicitlyUndefined: string = undefined; prop2ExplicitlyUndefined: number = undefined; prop1WithValue: string = 'Hello W
class foo {
prop1: string;
prop2: number;
prop1ExplicitlyUndefined: string = undefined;
prop2ExplicitlyUndefined: number = undefined;
prop1WithValue: string = 'Hello World!';
prop2WithValue: number = 123;
}
const myObject = new foo();
console.log(Object.getOwnPropertyNames(myObject));
console.log(Object.keys(myObject));
两个console.log都将输出:
[
"prop1ExplicitlyUndefined",
"prop2ExplicitlyUndefined",
"prop1WithValue",
"prop2WithValue"
]
有没有办法在不将属性设置为未定义或在构造函数中设置它们的情况下获取它们?没有,这是不可能的。转换为javascript时,类型会被删除,因此,如果一个类型是所有的类型,那么在运行时就什么都没有了。我想知道类型本身是否可能。。。有“keyof type”,但似乎不可能从中获得字符串数组