Búsqueda de sitios web

Error de TypeScript: La propiedad '...' falta en el tipo '...'


Me estoy encontrando con un error de TypeScript con este fragmento de código:

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

Dónde está el error:

El tipo ''{ preventDefault:() => void; stopPropagation:() => void; keyCode: number; }'' no se puede asignar al tipo ''KeyboardEvent''. Falta la propiedad ''altKey'' en el tipo ''{ preventDefault:() => void; stopPropagation:() => void; keyCode: number; }'.

Lo entiendo, es TypeScript, quiere que proporcione un KeyboardEvent completo. Pero la definición completa de KeyboardEvent es:

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;
}

Eso es mucho. Y estoy creando este evento con fines de pruebas unitarias, solo necesito las tres propiedades. ¿Cuál es la manera correcta de manejar esto? Estoy tratando de evitar simplemente declararlo como any y realmente tampoco quiero definir 21 propiedades.

¿Hay una mejor manera?

¡Gracias de antemano!

Respuesta #1

Intenta convertir al tipo deseado

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

Artículos relacionados