【问题标题】:Typescript classes extends Tuple打字稿类扩展元组
【发布时间】:2018-10-23 09:10:13
【问题描述】:
我正在寻找一种在 TypeScript 中扩展元组的方法。
在 C# 中,您可以轻松做到:
public class extends String { ... }
在 TypeScript 中,我希望能够编写如下内容:
export class Field extends [string, string] { ... }
有什么想法吗?
注意:我的目标是命名每个元组成员。
【问题讨论】:
标签:
typescript
inheritance
tuples
【解决方案1】:
如果您需要命名元组成员,最好使用接口。
如果你真的想派生元组,你可以这样做,但你需要一个元组构造函数作为基类。运行时的元组只是 javascript 中的数组,所以我们真正想要的是 Array 构造函数的类型别名,所以你真的继承了 Array:
const tupleConstructor: new (...p: [string, string]) => [string, string] = Array as any;
class Field extends tupleConstructor{
constructor(...p: [string, string]) {
super(...p);
(this as any).__proto__ = Field.prototype; // fix for inheriting arrays
}
get firstName() { return this[0]; }
get lastName() { return this[1];}
}
let a = new Field("1", "1");
let [a0, a1] = a;
console.log(`0: ${a0}`);
console.log(`1: ${a1}`);
let { firstName, lastName} = a;
console.log(`firstName: ${firstName}`);
console.log(`lastName: ${lastName}`);
【解决方案2】:
如果您的目标只是命名元组...
使用 typescript > 4.0(撰写本文时为 Beta 版),您现在可以命名元组:
type MyNamedTuple = [foo: string, bar: string];
这有助于在将 ...args 与元组泛型一起使用时完成代码