简体   繁体   English

从 typescript class 中删除未定义的元素

[英]Remove undefined elements from a typescript class

I have created a javascript class so it can be reused in the project.我创建了一个 javascript class 以便可以在项目中重用。

However, not all attributes are being set in the class at a given time.但是,并非所有属性都在给定时间在 class 中设置。

For example, this is the interface of the address class比如这是address class的接口

interface Address {
  use: Code,
  type: Code,
  text: string,
  city: string,
  district: string,
  state: string,
  postalCode: string,
  country: string,
  period: Period,
  value?: string | null,
}

class Address {
  constructor() {
  }
}

If you see the interface, you see that use has a type of Code which is another type of a class which has method called get() which will return a value or an Object如果您看到界面,您会看到use有一种Code类型,它是 class 的另一种类型,它具有称为get()的方法,该方法将返回一个值或 Object

The Address class has a getObject property which will create an object which can later be strigified by using JSON.strigify() Address class 有一个getObject属性,它将创建一个object稍后可以使用strigified JSON.strigify()

Here is how I'm going to set the values of an object created by this class,下面是我将如何设置由此 class 创建的 object 的值,

  const address = new Address()
  address.city = "Brisbane"
  address.country = "AUS"
  address.line.push("400, gStreet")
  address.postalCode = "4000"
  address.state = "QLD"
  address.use = new Code("work")

However, when i call address.getObject() this will trigger an error because the use is not set undefined and therefore can't call the method, get() .但是,当我调用address.getObject()时,这将触发错误,因为use未设置undefined ,因此无法调用方法get()

How can I solve this issue?我该如何解决这个问题?

Do I have to use something like lodash to remove undefined elements within an object before calling getObject() ?在调用getObject()之前,我是否必须使用 lodash 之类的东西来删除lodash中的未定义元素?

Thank you in advance.先感谢您。

I can comment due to StackOverflow:由于 StackOverflow,我可以发表评论:

// so this is a comment the typescript type system is structural meaning that u can use objects when needed and object ( class instance ) when needed for example, if u want typescript to help u with types and validations use ( classes, types, and interfaces ) otherwise u can use a plain javascript object as @Aluan Haddad said // so this is a comment the typescript type system is structural meaning that u can use objects when needed and object ( class instance ) when needed for example, if u want typescript to help u with types and validations use ( classes, types, and接口)否则你可以使用普通的 javascript object 正如@Aluan Haddad所说

U can read more here ( not mine ) typescript type system你可以在这里阅读更多(不是我的) typescript 类型系统

Good luck祝你好运

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM