我正在学习 TypeScript 和 Angular,我在书中遇到了一个无法编译的示例。恐怕我不知道如何解决这个问题。
这是无法编译的函数:
ngOnInit(): void {
const logger = fromEvent(this.input.nativeElement, 'keyup');
logger.pipe(
map((evt: KeyboardEvent) => evt.key.charCodeAt(0)),
filter(code => {
if (this.numeric) {
return !(code > 31 && (code < 48 || code > 57));
}
return true;
}),
tap(digit => this.keys += String.fromCharCode(digit))
).subscribe();
}
无法编译的具体行是:
map((evt: KeyboardEvent) => evt.key.charCodeAt(0)),
我看到以下错误:
Argument of type 'OperatorFunction<KeyboardEvent, number>' is not assignable to parameter of type 'OperatorFunction<unknown, number>'.
Type 'unknown' is not assignable to type 'KeyboardEvent'.ts(2345)
最佳答案
只需告诉 ts 该流将是键盘事件流
const logger = fromEvent<KeyboardEvent>(this.input.nativeElement, 'keyup');
这个<Type>
参数使记录器 Observable<KeyboardEvent>
并且 ts 不会提示
关于angular - 类型 'unknown' 无法分配给类型 'KeyboardEvent' .ts (2345),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66216814/