dlt
dlt

Reputation: 23

Type 'unknown' is not assignable to type 'KeyboardEvent'.ts (2345)

I'm learning TypeScript and Angular and I've run into an example in my book that won't compile. I'm afraid I don't know how to fix the problem.

Here is the function that won't compile:

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

The specific line that won't compile is:

map((evt: KeyboardEvent) => evt.key.charCodeAt(0)),

I see the following error:

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)

Upvotes: 2

Views: 1251

Answers (1)

Andrei
Andrei

Reputation: 12021

just tell ts that this stream will be stream of keyboard events

const logger = fromEvent<KeyboardEvent>(this.input.nativeElement, 'keyup');

this <Type> param makes logger Observable<KeyboardEvent> and ts won't complain about it

Upvotes: 3

Related Questions