Alex Vovchuk
Alex Vovchuk

Reputation: 2926

Augment custom type in TypeScript

I have broad usage of vertices array like Vertex[] And have many methods performing some actions on such array, like:

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

The idea is to create separate type like

type Polygon = Array<Vertex>;

and incapsulate all the methods there, like:

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

But actually the last line syntax doesn't work.

Question: How can I extend the custom type (like type Polygon = Array<Vertex>) with methods (like Polygon.prototype.doSomethingWith = () => true;)?

Update: I end up with just separate class Polygons that contains static methods accepting Vertex[] as input parameter. Usage like Polygons.doSomethingWith(polygon); Let me know if somebody has better ideas.

Upvotes: 0

Views: 156

Answers (1)

Michael Warner
Michael Warner

Reputation: 4217

This seems all wrong so please correct me if I'm not understanding you.

Currently, this is what you have assuming Vertex is just three points.

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

A Polygon is just an array of vertices so TypeScript does not see any functions attached to them.

If you want a Polygon to have functions you will need to make it into a class or an object something like this.

type Vertex = [number, number, number]

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

If you want your Polygons to only be an array of vertices and have a separate version have functions. Don't change the Polygon type as it will no longer be true to its structure but instead create a new type.

I think this is ugly as hell but it is fun to see what you can do.

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

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

Playground Link

enter image description here

Upvotes: 1

Related Questions