How to write a Kotlinesque extension function in Typescript?

Viewed 253

I Kotlin if I have an interface like this:

interface User {
    val name: String
    val email: String
}

I can write an extension function like this anywhere in the code:

fun User.toUserDto(): UserDto {
    TODO()
}

In Typescript if I have a similar interface:

export default interface User {
    name: string;
    email: string;
}

How can I augment it in a similar way? Is this a best practice in the language? Is there an alternative to this I don't know about?

2 Answers

You can augment classes like this, but it depends on the prototype property and there's no User.prototype (and no User value at all either).

You can also see this very long discussion. The explanation why the Kotlin/C# approach was rejected is here.

Interfaces in Typescript can only describe the shape of data, you cannot make instances of them or mutate them.

To write an extension function of an interface, you would need to implement the interface in a class, and add whatever you need on the class.

export class SomeUserClass implements User {
  name: string;
  email: string;
  
  constructor(name, email) {
    ...
  }

  toUserDto() {
    ...
  }
}
Related