skip to Main Content

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


  1. 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,
    }
    
    Login or Signup to reply.
  2. 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 …

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search