[英]Typescript classes extends Tuple
我正在尋找一種在 TypeScript 中擴展元組的方法。
在 C# 中,您可以輕松地執行以下操作:
public class extends String { ... }
在 TypeScript 中,我希望能夠寫出這樣的東西:
export class Field extends [string, string] { ... }
有任何想法嗎 ?
注意:我的目標是命名每個元組成員。
如果您需要命名元組成員,則最好使用一個界面。
如果您確實想要派生元組,則可以做到,但是您將需要一個元組構造函數作為基類。 運行時元組只是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}`);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.