如何在 Typescript 中编写 Kotlinesque 扩展函数?

问题描述

Kotlin 如果我有这样的 interface

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

我可以在代码的任何地方编写这样的扩展函数

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

Typescript 中,如果我有类似的 interface

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

我如何以类似的方式对其进行扩充?这是该语言的最佳实践吗?有没有我不知道的替代方法

解决方法

您可以增加 classes like this,但这取决于 prototype 属性,并且没有 User.prototype(也根本没有 User 值)。

您也可以看到这个 very long discussion。 Kotlin/C# 方法被拒绝的解释是 here

, Typescript 中的

Interfaces 只能描述数据的形状,你不能创建它们的实例或改变它们。

要编写接口的扩展函数,您需要在类中实现该接口,并在类中添加您需要的任何内容。

setState(prev=>({...prev,newState}))