gpt4 book ai didi

Typescript 类扩展了 Tuple

转载 作者:行者123 更新时间:2023-12-02 03:27:11 26 4
gpt4 key购买 nike

我正在寻找一种在 TypeScript 中扩展元组的方法。

在 C# 中,您可以轻松执行以下操作:

public class extends String { ... }

在 TypeScript 中,我希望能够编写如下内容:

export class Field extends [string, string] { ... }

有什么想法吗?

注意:我的目标是命名每个元组成员。

最佳答案

如果您需要命名元组成员,那么最好使用接口(interface)。

如果你确实想派生元组,你可以这样做,但你需要一个元组构造函数来充当基类。运行时的元组只是 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}`);

关于Typescript 类扩展了 Tuple,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52945274/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com