Typescript – 具有默认值的属性为undefined

huangapple go评论79阅读模式
英文:

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。

英文:
  1. export class EntityVM implements EntityModel {
  2. ...
  3. Properties...
  4. ...
  5. constructor(newEntity: EntityModel, isCollapsed = false) {
  6. ...
  7. Properties...
  8. ...
  9. this.isCollapsed = isCollapsed;
  10. }
  11. }
  12. public myFunction(myEntity: EntityVM) {
  13. //!! here myEntity.isCollapsed is undefined instead of false
  14. }
  15. public myEntity = new Array<EntityModel>();
  16. myFunction(myEntity)

When converting from EntityModel to EntityVM it does not add isCollapsed to false.

答案1

得分: 0

从你的代码来看,你使用了错误的语法,应该是这样的:

  1. class EntityModel {}
  2. export class EntityVM implements EntityModel {
  3. public isCollapsed;
  4. constructor(newEntity: EntityModel, isCollapsed = false) {
  5. this.isCollapsed = isCollapsed;
  6. }
  7. }
  8. const myEntity = new EntityVM({});
  9. function myFunction(myEntity: EntityVM) {
  10. console.log(myEntity); // => 将打印 Class EntityVM
  11. //!! myEntity 现在将具有默认值
  12. }
  13. myFunction(myEntity);

为了更好地理解,你可以在以下链接中查看示例:https://stackblitz.com/edit/typescript-tqirps?file=index.ts

希望这对你有所帮助!

英文:

From your code, you are use wrong syntax,
it should be:

  1. class EntityModel {}
  2. export class EntityVM implements EntityModel {
  3. public isCollapsed;
  4. constructor(newEntity: EntityModel, isCollapsed = false) {
  5. this.isCollapsed = isCollapsed;
  6. }
  7. }
  8. // public myEntity = new Array<EntityModel>() // please note, that `Array` is not your class.
  9. // you should be aware of it that typing dont have impact or value on runtime.
  10. const myEntity = new EntityVM({});
  11. function myFunction(myEntity: EntityVM) {
  12. console.log(myEntity); // => will print Class EntityVM
  13. //!! myEntity will have default value now
  14. }
  15. myFunction(myEntity);

For better understanding, here the sandbox you can see: https://stackblitz.com/edit/typescript-tqirps?file=index.ts

I hope it helps!

huangapple
  • 本文由 发表于 2023年3月7日 21:57:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75662924.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定