英文:
Typescript - Property with default value is undefined
问题
export class EntityVM implements EntityModel {
...
Properties...
...
constructor(newEntity: EntityModel, isCollapsed = false) {
...
Properties...
...
this.isCollapsed = isCollapsed;
}
}
public myFunction(myEntity: EntityVM) {
//!! here myEntity.isCollapsed is undefined instead of false
}
public myEntity = new Array
myFunction(myEntity)
在从EntityModel转换为EntityVM时,它没有将isCollapsed设置为false。
英文:
export class EntityVM implements EntityModel {
...
Properties...
...
constructor(newEntity: EntityModel, isCollapsed = false) {
...
Properties...
...
this.isCollapsed = isCollapsed;
}
}
public myFunction(myEntity: EntityVM) {
//!! here myEntity.isCollapsed is undefined instead of false
}
public myEntity = new Array<EntityModel>();
myFunction(myEntity)
When converting from EntityModel to EntityVM it does not add isCollapsed to false.
答案1
得分: 0
从你的代码来看,你使用了错误的语法,应该是这样的:
class EntityModel {}
export class EntityVM implements EntityModel {
public isCollapsed;
constructor(newEntity: EntityModel, isCollapsed = false) {
this.isCollapsed = isCollapsed;
}
}
const myEntity = new EntityVM({});
function myFunction(myEntity: EntityVM) {
console.log(myEntity); // => 将打印 Class EntityVM
//!! myEntity 现在将具有默认值
}
myFunction(myEntity);
为了更好地理解,你可以在以下链接中查看示例:https://stackblitz.com/edit/typescript-tqirps?file=index.ts
希望这对你有所帮助!
英文:
From your code, you are use wrong syntax,
it should be:
class EntityModel {}
export class EntityVM implements EntityModel {
public isCollapsed;
constructor(newEntity: EntityModel, isCollapsed = false) {
this.isCollapsed = isCollapsed;
}
}
// public myEntity = new Array<EntityModel>() // please note, that `Array` is not your class.
// you should be aware of it that typing dont have impact or value on runtime.
const myEntity = new EntityVM({});
function myFunction(myEntity: EntityVM) {
console.log(myEntity); // => will print Class EntityVM
//!! myEntity will have default value now
}
myFunction(myEntity);
For better understanding, here the sandbox you can see: https://stackblitz.com/edit/typescript-tqirps?file=index.ts
I hope it helps!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论