定制扩展方法在打字稿中
好吧,我试图为我的界面学生创建扩展方法
declare global {
interface Student {
CourseOpted(): String;
}
}
Student.prototype.CourseOpted = function(): string {
return 'some-string';
}
export {};
,当我将光标放在学生身上时: - `
`学生''仅引用一种类型,但在这里被用作值。 正在引用本文: - https://www.c-sharpcorner.com/article/article/article/learn-about-elearn-about-extension-extension-extension-method-mothod-mothod-mothod-mothod-mothod-method-method-in-typescript/#:~ :text =扩展%2DMethod%20GIVES%20 you%20,任何%20DATA%2dtype%20You%20want 。
我可以注意到的是; - 当我们扩展界面类(例如字符串,数字,数组)的类时。扩展方法是可能的。那为什么不作为上述示例。 请帮我!解决此错误
非常感谢:)
编辑: - 因此,我们发现此TS扩展方法回购: - https://github.com/github.com/staeke/staeke/ts-ts--ts---------扩展方法
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
接口
是编译的时间元素。当您将打字稿编译到JavaScript中时,它不会为接口
发出任何内容。接口
纯粹存在于编译时(受益于打字稿)。它适用于字符串,数字等的原因,因为它们存在于运行时。
如果您需要对函数的不同实现
student
是class
具有默认函数实现的,并允许子类在需要时覆盖功能实现。如果您想要静态实现
Student
类中的静态功能interface
are a compiled time element. When you compile Typescript into Javascript it does not emit anything for aninterface
. Theinterface
purely exist at compile time (to benefit typescript).The reason why it works for String, Number, etc. because they exist at runtime.
If you want different implementation of the function
Student
as aclass
with default function implementation and allow a sub-class to override the functional implementation as and when required.If you want a static implementation
Student
classStudent
是接口
,而不是类
您应该在进行任何更改之前创建类并导入该类别。也许最好只是创建新课程。如果您从服务器中获取学生数据,也可以向其添加序列化。Typescript Playground Link
Student
is aninterface
, notclass
you should create class and import it before making any changes. Maybe it is better just to create new class. You may also add serialization to it, if you take students data from server.Typescript Playground Link