简体   繁体   English

如何在不使用接口的情况下定义对象属性的类型

[英]How to define type of object property without using an interface

tickList is (or should be) an Array of type number tickList 是(或应该是)类型为 number 的数组

fpsObject = {
  maxSamples: 100,
  tickIndex: 0,
  tickSum: 0,
  tickList: []
}

Can I enforce this type without creating an interface?我可以在不创建接口的情况下强制执行这种类型吗? Or must I create an interface to do this?或者我必须创建一个接口来做到这一点? Thanks in advance.提前致谢。 I would rather avoid creating an interface if at all possible.如果可能的话,我宁愿避免创建界面。 I've got too many interface files already!我已经有太多的界面文件了!

You can use as to type it:您可以使用 as 键入它:

const fpsObject = {
  maxSamples: 100,
  tickIndex: 0,
  tickSum: 0,
  tickList: [] as number[]
}

Typescript Playground 打字稿游乐场

const fpsObject = {
  maxSamples: 100,
  tickIndex: 0,
  tickSum: 0,
  tickList: Array<number>()
}
console.log(fpsObject)

// You can use This way Also.

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

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