带KnockoutJS的TypeScript怎么实现?

  • 回答 (2)
  • 关注 (0)
  • 查看 (13)

是否有使用KnockoutJS实现TypeScript的样本?是怎么工作的?

lllspeedlllspeed提问于
742512027cdb不要轻易地考验人性回答于
已采纳
缪雪儿sakura回答于

我制作了这个小界面来获取Knockout的静态类型:

interface ObservableNumber {
        (newValue: number): void;               
        (): number;                             
        subscribe: (callback: (newValue: number) => void) => void;
}
interface ObservableString {
        (newValue: string): void;               
        (): string;                             
        subscribe: (callback: (newValue: string) => void) => void;
}
interface ObservableBool {
    (newValue: bool): void;             
    (): bool;                               
    subscribe: (callback: (newValue: bool) => void) => void;
}

interface ObservableAny {
    (newValue: any): void;              
    (): any;                                
    subscribe: (callback: (newValue: any) => void) => void;
}

interface ObservableStringArray {
    (newValue: string[]): void;
    (): string[];
    remove: (value: String) => void;
    removeAll: () => void;
    push: (value: string) => void;
    indexOf: (value: string) => number;
}

interface ObservableAnyArray {
    (newValue: any[]): void;
    (): any[];
    remove: (value: any) => void;
    removeAll: () => void;
    push: (value: any) => void;
}

interface Computed {
    (): any;
}

interface Knockout {
    observable: {
        (value: number): ObservableNumber;
        (value: string): ObservableString;
        (value: bool): ObservableBool;
        (value: any): ObservableAny;
    };
    observableArray: {
        (value: string[]): ObservableStringArray;
        (value: any[]): ObservableAnyArray;
    };
    computed: {
        (func: () => any): Computed;
    };
}

将其放入“Knockout.d.ts”中,然后从自己的文件中引用它。正如所看到的,它将从泛型(根据规范来的)中获益良多。

我只为ko.watch able()创建了几个接口,但是ko.Computed()和ko.watableArray()可以很容易地添加到相同的模式中。最新情况:我修正了订阅()的签名,并添加了计算()和观察者数组()的例子。

若要从自己的文件中使用,请在顶部添加以下内容:

/// <reference path="./Knockout.d.ts" />
declare var ko: Knockout;

扫码关注云+社区