简体   繁体   English

TypeScript:ArrayLike接口缺少索引签名

[英]TypeScript: index signature is missing with ArrayLike interface

I tried to use TypeScript built-in interface, ArrayLike , but still got the error message like following: 我尝试使用TypeScript内置接口ArrayLike ,但仍然收到如下错误消息:

Error:(12, 11) TS2420: Class 'Point' incorrectly implements interface 'ArrayLike'. 错误:(12、11)TS2420:类“ Point”错误地实现了接口“ ArrayLike”。 Index signature is missing in type 'Point'. 类型“ Point”中缺少索引签名。

interface ArrayLike<T> {
    length: number;
    [n: number]: T;
}

class Point implements ArrayLike<number> {
    [0]: number = 10;
    length: number = 1;
}

How can I solve this problem? 我怎么解决这个问题? (or any workaround?) (或任何解决方法?)

How to implement the interface ArrayLike : 如何实现ArrayLike接口:

class Point implements ArrayLike<number> {
    [n: number]: number;
    length: number = 1;
    [0]: number = 10;
}

let p = new Point()
p[23] = 34; // ok
p[23] = "34"; // Error: Type 'string' is not assignable to type 'number'

If you want your Point to be an array then why not just extending the Array class? 如果您希望Point是一个数组,那么为什么不扩展Array类呢?

class Point extends Array<number> {
    // add Point array methods here
}

This way Point will implement the ArrayLike<number> interface automatically. 这样, Point将自动实现ArrayLike<number>接口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM