获取自定义类型数组的长度

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

Typescript: Get length of custom typed array

问题

如何获取自定义类型数组的长度?

例如:

type TMyArray = IProduct[]

interface IProduct {
  cost: number,
  name: string,
  weight: number
}

那么,在这里如何获取数组长度:

const testArr: TMyArray = [...一些数组元素]

console.log(testArr.length) // 返回类型错误,类型“IDocument”上不存在属性'length'

主要问题是如何在TypeScript中正确做到这一点。

我尝试将长度添加到 IProduct 中,但似乎是错误的:

interface IProduct = {
  cost: number,
  name: string,
  weight: number,
  length: number,
}
英文:

Can somebody tell me how to get array length of custom typed array?

E.g:

type TMyArray = IProduct[]

interface IProduct {
  cost: number,
  name: string,
  weight: number
}

So, how to get length here:

const testArr: TMyArray = [...some array elements]

console.log(testArr.length) // returning type error Property 'length' does not exist on type 'IDocument'

Main question is how to do it right with typescript

I've tried to add length to IProduct, but it seems wrong

interface IProduct = {
  cost: number,
  name: string,
  weight: number,
  length: number,
}

答案1

得分: 0

你的接口声明不正确。它不需要一个 = 符号。因此,应该是:

interface IProduct {
  cost: number,
  name: string,
  weight: number,
  length: number,
}
英文:

The declaration of your interface is incorrect. It does not need a = sign. So, it should be:

interface IProduct {
  cost: number,
  name: string,
  weight: number,
  length: number,
}

答案2

得分: 0

I suggest using, as type for testArr, an actual Array with its contents as generic.

const testArr: Array<IProduct> = [...some array elements]

This way, the whole thing works on aforementioned playground https://www.typescriptlang.org/play :

interface IProduct {
  cost: number,
  name: string,
  weight: number
}

const testArr: Array<IProduct> = []

console.log(testArr.length)

Edit: Oh, now I'm confused; your code works there, too, and why shouldn't it ... hmmm ...

英文:

I suggest using, as type for testArr, an actual Array with its contents as generic.

const testArr: Array&lt;IProduct&gt; = [...some array elements]

This way, the whole thing works on aforementioned playground https://www.typescriptlang.org/play :

interface IProduct {
  cost: number,
  name: string,
  weight: number
}

const testArr: Array&lt;IProduct&gt; = []

console.log(testArr.length)

Edit: Oh, now I'm confused; your code works there, too, and why shouldn't it ... hmmm ...

huangapple
  • 本文由 发表于 2023年2月23日 23:49:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/75547178.html
匿名

发表评论

匿名网友

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

确定