我使用的是带有严格模式的类型记录,我们为类似于这个[key: string]: any的接口编写索引签名,但是我们应该如何为像KeyboardEvent这样的事件编写索引签名,编写得到错误'KeyboardEvent' has no index signature.ts(7017)的代码。
public checkInput(event: KeyboardEvent): void {
if (event['keyIdentifier'] !== undefined) {
keyCode = event['keyIdentifier'];
}
}发布于 2019-05-13 07:51:19
当MDN 条目声明时,这是一个非标准的、被废弃的特性:
不建议使用的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;
}
}
}https://stackoverflow.com/questions/56107789
复制相似问题