簡體   English   中英

在 TypeScript 中增加自定義類型

[英]Augment custom type in TypeScript

我廣泛使用了像Vertex[]這樣的頂點數組,並且有很多方法可以對這樣的數組執行一些操作,例如:

public doSomethingWith(polygon: Vertex[]) {...}

這個想法是創建單獨的類型,如

type Polygon = Array<Vertex>;

並封裝那里的所有方法,例如:

Polygon.prototype.doSomethingWith = () => true;

但實際上最后一行語法不起作用。

問題:如何使用方法(如Polygon.prototype.doSomethingWith = () => true; )擴展自定義類型(如type Polygon = Array<Vertex> )?

更新:我最終得到了單獨的類Polygons ,其中包含接受Vertex[]作為輸入參數的靜態方法。 用法類似Polygons.doSomethingWith(polygon) 如果有人有更好的想法,請告訴我。

這似乎全錯了,所以如果我不理解你,請糾正我。

目前,這就是您假設 Vertex 只有三個點的情況。

type Vertex = [number, number, number]
type Polygon = Array<Vertex>;
const Poly: Polygon = [[1,2,3], [1,2,3]]

Polygon 只是一個頂點數組,因此 TypeScript 看不到任何附加到它們的函數。

如果您希望 Polygon 具有函數,則需要將其制作為類或對象,例如這樣的內容。

type Vertex = [number, number, number]

class Polygon {
    vertices: Vertex[] = []
    doSomethingWith () {
        // do something to this.vertices
    }
}
const Poly = new Polygon()
Poly.doSomethingWith()

如果你希望你的多邊形只是一個頂點數組並且有一個單獨的版本有函數。 不要更改 Polygon 類型,因為它不再符合其結構,而是創建一個新類型。

我認為這很丑陋,但看看你能做什么很有趣。

type Vertex = [number, number, number]
type Polygon = Array<Vertex>;
type FnPolygon = Polygon & {
    doSomething: () => any
} 

function PolyToFnPoly (poly:Polygon):FnPolygon {
    const fnPoly = pol...

游樂場鏈接

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM