typescript 界面内的打字稿默认功能

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36110184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:21:35  来源:igfitidea点击:

typescript default function inside interface

typescript

提问by Angel Angel

This is working

这是工作

interface test{
    imp():number;
}

but it is possible to implement a function inside.

但可以在内部实现一个功能。

interface test{
    imp():number{
      // do something if it is not overwritten
    }
}

This is not working in typescript for me, but there may be some reserved word, for example default or similar, to implement a function inside an interface that is not overwritten if the default work.

这对我来说在打字稿中不起作用,但可能有一些保留字,例如 default 或类似的,以在默认工作时不会覆盖的接口内实现函数。

采纳答案by basarat

No. TypeScript Interfaces are not something available at runtime, that is they are completely absent in the generated JavaScript.

不可以。TypeScript 接口在运行时不可用,也就是说它们在生成的 JavaScript 中完全不存在。

Perhaps you meant to use class:

也许您打算使用class

class Test{
    imp(){return 123}
 }

回答by realh

I've discovered that Typescript seems to allow an interface and another class or object to share the same name. So you can do this:

我发现 Typescript 似乎允许接口和另一个类或对象共享相同的名称。所以你可以这样做:

interface test {
    imp(): number
}

class test {
    static imp() { return 123 }
}

class test2 /* extends something */ implements test {
    imp() { return test.imp() }
}

It's a pity TS doesn't support function implementations in interfaces, like Kotlin does, to save us writing the wrapper methods, because it could be implemented quite easily in the underlying Javascript.

遗憾的是 TS 不支持接口中的函数实现,就像 Kotlin 那样,以节省我们编写包装器方法,因为它可以很容易地在底层 Javascript 中实现。