2016-12-16 116 views
2

我正在爲打字稿誤差這段代碼:打字稿錯誤:屬性「...」缺失型「...」

let event: KeyboardEvent = { 
    preventDefault:() => { }, 
    stopPropagation:() => { }, 
    keyCode: 75 
}; 

錯誤所在:

Type '{ preventDefault:() => void; stopPropagation:() => void; keyCode: number; }' is not assignable to type 'KeyboardEvent'. Property 'altKey' is missing in type '{ preventDefault:() => void; stopPropagation:() => void; keyCode: number; }'.

我明白了,它是TypeScript,它希望我提供完整的KeyboardEvent。但KeyboardEvent的全部定義是:

interface KeyboardEvent extends UIEvent { 
    readonly altKey: boolean; 
    readonly char: string | null; 
    readonly charCode: number; 
    readonly ctrlKey: boolean; 
    readonly key: string; 
    readonly keyCode: number; 
    readonly locale: string; 
    readonly location: number; 
    readonly metaKey: boolean; 
    readonly repeat: boolean; 
    readonly shiftKey: boolean; 
    readonly which: number; 
    readonly code: string; 
    getModifierState(keyArg: string): boolean; 
    initKeyboardEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, keyArg: string, locationArg: number, modifiersListArg: string, repeat: boolean, locale: string): void; 
    readonly DOM_KEY_LOCATION_JOYSTICK: number; 
    readonly DOM_KEY_LOCATION_LEFT: number; 
    readonly DOM_KEY_LOCATION_MOBILE: number; 
    readonly DOM_KEY_LOCATION_NUMPAD: number; 
    readonly DOM_KEY_LOCATION_RIGHT: number; 
    readonly DOM_KEY_LOCATION_STANDARD: number; 
} 

這是很多。我爲單元測試創​​建這個事件,我只需要這三個屬性。處理這個問題的正確方法是什麼?我試圖避免簡單地聲明它爲any,我也不想定義21個屬性。

有沒有更好的方法?

在此先感謝!

+2

你試過雙鑄造? ('evt:KeyboardEvent =({...} as any)作爲KeyboardEvent') – olivarra1

+2

@ olivarra1即使只是一個簡單的單投就能勝任。 '讓事件:的KeyboardEvent = { \t的preventDefault:()=> {}, \t stopPropagation:()=> {}, \t鍵代碼:75 }作爲的KeyboardEvent;'。不知道TypeScript是否允許這樣做。很棒的發現。 –

+0

如果你只需要3個屬性,你可以定義你自己的接口只有這3個屬性,並在你的代碼中使用它。不要使用真正的'KeyboardEvent',只要確保真實的事件可以分配給你的。 – artem

回答

2

嘗試鑄造所需的類型

let event: KeyboardEvent = { 
    preventDefault:() => { }, 
    stopPropagation:() => { }, 
    keyCode: 75 
} as KeyboardEvent;