Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何获取所有类属性,即使是typescript的可选属性?_Typescript - Fatal编程技术网

如何获取所有类属性,即使是typescript的可选属性?

如何获取所有类属性,即使是typescript的可选属性?,typescript,Typescript,当我试图从类中获取属性名时,getOwnPropertyNames只返回具有值的属性 是否有一种方法可以获取所有属性,而不仅仅是具有值的属性 Klass类{ 第一个值:字符串; secondValue!:字符串; 构造函数(){ this.firstValue='withValue'; log(Object.getOwnPropertyNames(this)); } } 新Klass(); 结果: ['firstValue'] 不幸的是,没有任何值的道具将无法被用户看到 将道具设置为,例如,f

当我试图从类中获取属性名时,
getOwnPropertyNames
只返回具有值的属性

是否有一种方法可以获取所有属性,而不仅仅是具有值的属性

Klass类{
第一个值:字符串;
secondValue!:字符串;
构造函数(){
this.firstValue='withValue';
log(Object.getOwnPropertyNames(this));
}
}
新Klass();
结果:

['firstValue']

不幸的是,没有任何值的道具将无法被用户看到

将道具设置为,例如,
false
undefined
,将显示道具

this.test_1;
本测试_2=错误;
本测试_3=未定义;
const allPropertyNames=Object.getOwnPropertyNames(this);
console.log(allPropertyNames.includes('test_1'));//错误的
console.log(allPropertyNames.includes('test_2'));//符合事实的

console.log(allPropertyNames.includes('test_3'));//TRUE
将默认值放入属性将允许您获取该对象中的所有属性名称,因为所有无值属性均未定义,所以打印时该属性在对象中不存在


但你为什么需要这些信息呢?在问题代码示例中,您已经知道您需要或将要使用的所有名称。

您应该在构造函数中预先设置所有可能的属性。可选值应设置为null

constructor(){
this.firstValue='first';
this.secondValue=null;
log(Object.getOwnPropertyNames(this));
}

没有值的属性是不存在的属性。我不知道你想做什么。那不是编译JavaScript。实际上我在使用Typescript。。尝试时,vanilla js按预期工作。然后将javascript标记替换为typescript并修复title@Samathingamajig完成。。对不起。。