0

I expect that a class return an array when I new it

class MyArray {
  constructor(){

  }
}

const myArray = new MyArray()
Array.isArray(myArray) // Should be true

I used to write it in this way:

class MyArray {
  constructor(){
    const arry = new Array()
    return arry
  }
}

But when I write in Typescript,the return value arry is not the type of MyArray, so it prompt an error.

How to fixed this problem?

5
  • Why do you want to achieve such strange behavior? Commented Dec 13, 2017 at 9:42
  • you are looking for collection class Commented Dec 13, 2017 at 9:42
  • Not sure what you are trying to achieve. Why should Array.isArray(myArray) be true when it's obviously a class and not an array. Commented Dec 13, 2017 at 9:43
  • Possible dup of: stackoverflow.com/questions/3261587/… Commented Dec 13, 2017 at 9:55
  • I want to customize my array-like data structure Commented Dec 13, 2017 at 9:56

1 Answer 1

7

Just extend Array and return true in the constructor

class MyArray extends Array{
  constructor(){
    super()
  }
}

Demo

class MyArray extends Array{
  constructor(){
    super()
  }
}

myArray2 = new MyArray()
console.log(Array.isArray(myArray2));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.