[英]How to Construct an array by es6 class
I expect that a class return an array when I new
it 我期望一个类在我new
时返回一个数组
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. 但是,当我在写打字稿,返回值arry
不是MYARRAY的类型,所以它提示错误。
How to fixed this problem? 如何解决这个问题?
Just extend Array
and return true
in the constructor 只需扩展Array
并在构造函数中 return true
class MyArray extends Array{
constructor(){
super()
}
}
Demo 演示版
class MyArray extends Array{ constructor(){ super() } } myArray2 = new MyArray() console.log(Array.isArray(myArray2));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.