gpt4 book ai didi

typescript 错误 : Property '...' is missing in type '...'

转载 作者:搜寻专家 更新时间:2023-10-30 21:08:43 26 4
gpt4 key购买 nike

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

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

错误所在:

类型 '{ preventDefault: () => void;停止传播:()=>无效;键码:数字; }' 不可分配给类型 'KeyboardEvent'。
类型 '{ preventDefault: () => void; 中缺少属性 'altKey';停止传播:()=>无效;键码:数字; }'.

我明白了,它是 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 个属性。

有没有更好的办法?

提前致谢!

最佳答案

尝试转换为所需的类型

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

关于 typescript 错误 : Property '...' is missing in type '...' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41186335/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com