TypeScript with KnockoutJS

后端 未结 6 1423
粉色の甜心
粉色の甜心 2020-12-22 16:28

Is there any sample of using TypeScript with KnockoutJS? I\'m just curious as to how they would work together?

Edit

Here is what I have, seems to work

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-22 16:53

    I made this little interface to get static types for 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;
        };
    }
    

    Put it in "Knockout.d.ts" and then reference it from your own files. As you can see, it would benefit greatly from generics (which are coming according to the specs).

    I only made a few interfaces for ko.observable(), but ko.computed() and ko.observableArray() can be easily added in the same pattern. Update: I fixed the signatures for subscribe() and added examples of computed() and observableArray().

    To use from your own file, add this at the top:

    /// 
    declare var ko: Knockout;
    

提交回复
热议问题