Typescript: Extension methods for interfaces

Created on 12 Jun 2018  路  8Comments  路  Source: microsoft/TypeScript

Apologies I this is a dup.

The situation comes up often. I define an interfaces for my API JSON responses and I wish they were classes so I could define instance methods on them. Say for mutation, or just helpful convenience methods.

Sure I can use standalone functions that take the interface as the first parameter but discover-ability sucks.

Something like this:

interface Rect {
    x: number;
    y: number;
    width: number;
    height: number;
}

function area(rect: this Rect): number {
    return rect.widht * rect.height;
}
Duplicate

Most helpful comment

@oliverjanik I'm facing the same limitation (no instance methods on objects deserealized from JSON). What's the best way you found to work around it?

All 8 comments

Unfortunately if the proposal is that that syntax enables users to write

declare let x: Rect;
x.area()

then this would be type-directed syntax, and also falls out of our design goals in that it extends ECMAScript past the type space. You might want to keep an eye on the pipeline operator (|>, tracked at #17718) or the less-likely bind operator (::, tracked at #3508).

Interesting. Thanks for pointers.

Different operator, however, does not fix discoverability problem as everyone is just used to typing dot and get suggestions.

@mhegazy Wasn't #9 closed due to inactivity?

Edit: Sorry, I thought you closed this issue.

@oliverjanik no, read the thread, it was closed because it was deemed out of scope, because there are some major problems with implementation that make it not practical to be considered. Because people were not reading the thread and understanding that it is not implementable, the whole thread had to be locked.

This is asking exactly for a feature which is out of scope, so it is a duplicate.

I understand it's impractical and type driven syntax.

On the other hand it's impossible in plain JS because JS doesn't know about interfaces. They're compiled away.

So while you can monkey-patch classes in JS, interfaces will never be possible.

Not sure if there's any way forward on this.

Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

@oliverjanik I'm facing the same limitation (no instance methods on objects deserealized from JSON). What's the best way you found to work around it?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

rbuckton picture rbuckton  路  139Comments

OliverJAsh picture OliverJAsh  路  242Comments

rwyborn picture rwyborn  路  210Comments

Taytay picture Taytay  路  174Comments

Gaelan picture Gaelan  路  231Comments