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

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

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!

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:

确定