Rah*_*han 4 javascript interface typescript
在JavaScript中,直接向prototype任何类型添加函数和成员.我试图在TypeScript中实现相同的目的如下:
interface Date
{
Minimum: Date;
}
Date.prototype.Minimum = function () { return (new Date()); }
Run Code Online (Sandbox Code Playgroud)
这会产生以下错误:
Type '() => Date' is not assignable to type 'Date'.
Property 'toDateString' is missing in type '() => Date'.
Run Code Online (Sandbox Code Playgroud)
考虑到TS是强类型的,我们怎么能实现这个目标呢?
由于我在TS中编写自定义实用程序库,所以我宁愿不使用JS.
obe*_*obe 20
接口不会被转换为JS,它们只是用于定义类型.
您可以创建一个从第一个继承的新接口:
interface IExtendedDate extends Date {
Minimum: () => Date;
}
Run Code Online (Sandbox Code Playgroud)
但是对于实际的实现,您需要定义一个类.例如:
class ExtendedDate implements IExtendedDate {
public Minimum(): Date {
return (new ExtendedDate());
}
}
Run Code Online (Sandbox Code Playgroud)
但请注意,您可以在没有界面的情况下执行所有操作.
你可以这样:
interface Date
{
Minimum(): Date;
}
(<any>Date.prototype).Minimum = function () { return (new Date()); }
let d = new Date();
console.log(d.Minimum());
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助。
| 归档时间: |
|
| 查看次数: |
9446 次 |
| 最近记录: |