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,
}
2
Answers
The declaration of your interface is incorrect. It does not need a
=
sign. So, it should be:Example: TypeScript Playground
Interface documentation
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 :
Edit: Oh, now I’m confused; your code works there, too, and why shouldn’t it … hmmm …