英文:
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<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 ...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论