我希望当我new
一个类时返回一个数组
class MyArray {
constructor(){
}
}
const myArray = new MyArray()
Array.isArray(myArray) // Should be true
我以前是这样写的:
class MyArray {
constructor(){
const arry = new Array()
return arry
}
}
但是我用Typescript写的时候,返回值arry
不是MyArray的类型,所以提示错误。
如何解决这个问题?
最佳答案
只需在构造函数中扩展Array
并返回true
class MyArray extends Array{
constructor(){
super()
}
}
演示
class MyArray extends Array{
constructor(){
super()
}
}
myArray2 = new MyArray()
console.log(Array.isArray(myArray2));
关于javascript - 如何通过es6类构造数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47789796/