我必须为驻留在全局范围内的现有JavaScript库编写一些类型定义:
[assembly: ExportRenderer(typeof(NewButton), typeof(NewButtonRenderer))]
namespace WinPhone
{
class NewButtonRenderer : ButtonRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
{
base.OnElementChanged(e);
if (Control != null)
{
Control.ApplyTemplate();
var border = new Border
{
CornerRadius = new System.Windows.CornerRadius(10),
};
Control.Foreground = new SolidColorBrush(Colors.White);
Control.Background = new SolidColorBrush(System.Windows.Media.Color.FromArgb(255, 130, 186, 132));
Control.BorderBrush = new SolidColorBrush(System.Windows.Media.Color.FromArgb(255,45,176,51)) ;
Control.BorderThickness = new System.Windows.Thickness(0.8);
}
}
}
}
d.ts定义是这样的:
window.ThridPartyLibrary = {};
或者像这样(取决于库的'形状'):
declare module ThridPartyLibrary
{
var foo: any;
...
}
然而,在这两种情况下,都不可能使库的类型本身可用,以便例如我可以将它传递给函数:
declare var ThridPartyLibrary : IThridPartyLibrary
interface IThridPartyLibrary
{
foo: any;
...
}
在这种简单的情况下,可以通过第二(接口)方法传递接口:
declare function bar( library: ThirdPartyLibrary ): void;
问题是接口方法不起作用,因为我有其他的东西,比如我想描述的嵌套子模块和枚举:
declare function bar( library: IThirdPartyLibrary ): void;
那么还有其他方法来描述这个库吗?我这样做的原因是我想将库作为服务注入AngularJS函数,我想在函数签名中提供类型信息。
提前感谢您的任何帮助!
答案 0 :(得分:1)
您可以使用mixing,如下所示:
// The interface (or declare class)
interface ThirdPartyLibrary
{
// with properties and methods
foo: any;
}
// The module with sub modules, enums, ...
declare module ThirdPartyLibrary
{
module EvenMoreStuff
{
var bar: any;
}
enum Things
{
Thing1 = 0,
Thing2 = 1,
}
}
// now you can use the interface module mix as type for param
declare function bar(library: ThirdPartyLibrary): void;
function bar2(library: ThirdPartyLibrary, thing: ThirdPartyLibrary.Things) {
alert(thing+library.foo);
}
bar2({ foo: ":)" }, 0);
在游乐场(Sample)
中工作答案 1 :(得分:0)
使用typeof
运算符
declare function bar( library: typeof ThirdPartyLibrary ): void;