我在严格模式下使用打字稿,我们为类似[key: string]: any
这样的接口写索引签名,但是我们应该如何为诸如KeyboardEvent等事件编写索引签名,导致代码出错'KeyboardEvent' has no index signature.ts(7017)
public checkInput(event: KeyboardEvent): void {
if (event['keyIdentifier'] !== undefined) {
keyCode = event['keyIdentifier'];
}
}
答案 0 :(得分:0)
正如MDN entry所述,这是一项非标准的,已弃用的功能:
不推荐使用的KeyboardEvent.keyIdentifier只读属性返回一个“键标识符”字符串,该字符串可用于确定按下了哪个键。其不建议使用的替换为KeyboardEvent.key。
如果您坚持使用它,只需将keyIdentifier
强制转换为KeyboardEvent
的适当键即可:
public checkInput(event: KeyboardEvent): void {
if (event['keyIdentifier' as 'key'] !== undefined) {
const keyCode = event['keyIdentifier' as 'key'];
}
}
其他选项将强制转换为any
((event as any)['keyIdentifier']
)或扩大全局类型:
interface KeyboardEvent {
keyIdentifier: string
}
class s {
public checkInput(event: KeyboardEvent): void {
if (event.keyIdentifier !== undefined) {
const keyCode = event.keyIdentifier;
}
}
}