2017-11-25 114 views
1

我有一個接口:如何在對象Typescript中使用這個描述符?

export interface DisabledFormFields { 
    active: number, 
    functions: { 
    get?($event: any): string; 
    set?($event: any): void; 
    } 
} 

然後我創建基於此intreface對象:

instance.set({index: 0}); 
instance.get({}); 

爲什麼我不能獲得財產active使用:

var instance = { 
    active: 0, 
    set(event) { 
     this.active = event.index; 
    }, 
    get(event) { 
     return "-"; 
    }, 
} 

使用此this描述符裏面的方法對象?

+3

你會得到什麼錯誤?我看到的第一件事是接口和對象不匹配。 (函數子對象丟失) –

+0

爲什麼你用兩個不同版本的TypeScript標記了這個? – Amy

+0

沒有任何錯誤 – Oleg

回答

2

你(輕微改變)對象:

var instance: Disable = { 
    active: 0, 
    set(event: any) { 
     this.active = event.index; 
    }, 
    get(event: any) { 
     event;// doing nothing but dealing with the noUnusedParameteres 
     return "-"; 
    }, 
} 

能有這樣的接口:

interface Disable { 
    active: number; 
    set?(event: any): void; // not necessarily optional 
    get?(event: any): string;// idem 
} 

如果set和get是可選的,它是需要使用型後衛,看看他們是定義:

if(instance.set) { 
    instance.set({index: 1});// it is defined in this block 
} 

在您的原始界面中,您有這個內部對象...

functions: { 
    get?($event: any): string; 
    set?($event: any): void; 
} 

你沒有包含在你的對象中。該對象也沒有實現該接口,因爲結構不同,並且在var聲明中沒有註釋。你必須改變界面或你的對象。

+0

我真的不明白你的解決方案,對我來說,這是我發佈的相同。它在對象內部沒有作用:'this.active = event.index;' – Oleg

+0

它看起來是一樣的,因爲它是相同的(因此稍微改變了)。它只是給出了一些想法,爲什麼你的界面在這種情況下沒有用處。嘗試移除界面,不要聲明類型,只需使用已定義的對象。如果它給出了一些編譯錯誤,請更新錯誤代碼的問題,如「TS1234出錯了」 – 2017-11-25 22:09:46

+0

您可以嘗試在這裏,它不起作用:https://www.typescriptlang.org/play/ – Oleg

1

我用的操場和嘗試這個

var instance = { 
    active: 0, 
    set(event) { 
     this.active = event.index; 
    }, 
    get(event) { 
     return "<h1>-</h1>"; 
    }, 
} 

instance.set({index: 0}); 
instance.get({}); 

document.writeln(instance.get({})); 

它transpiled這樣:

var instance = { 
    active: 0, 
    set: function (event) { 
     this.active = event.index; 
    }, 
    get: function (event) { 
     return "<h1>-</h1>"; 
    }, 
}; 
instance.set({ index: 0 }); 
instance.get({}); 
document.writeln(instance.get({})); 

而且在運行單擊時在瀏覽器中打開一個新的標籤與此:

-

+0

操場可能沒有進行所有嚴格的類型檢查,因爲它沒有拒絕沒有類型註釋的_event_參數。 – 2017-11-25 22:26:47

相關問題