TypeScript错误:属性' ...'类型' ...&{39;

时间:2016-12-16 14:17:48

标签: typescript

我用这段代码遇到了TypeScript错误:

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个属性。

有更好的方法吗?

提前致谢!

1 个答案:

答案 0 :(得分:3)

尝试投射到所需的类型

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