1

enter image description here

enter image description here

enter image description here

Typescript does not like the parameter type of my then callback:

Argument of type '(value: T) => void' is not assignable to parameter of 
type '(value: unknown) => void | PromiseLike<void>'.
  Types of parameters 'T' and 'value' are incompatible.
    Type 'unknown' is not assignable to type 'T'.
Greg K
  • 10,770
  • 10
  • 45
  • 62
sarv19
  • 31
  • 5
  • 2
    Apparently `this.booksServices.getSingleBook` (which you haven't shown) returns a `Promise`, so there's no guarantee you'll get a `Book` back. Please give a [mre] **as text**. – jonrsharpe Jun 22 '21 at 13:24
  • @jonrsharpe I just edited the question with code for booksServices.getSingleBook – sarv19 Jun 22 '21 at 13:29
  • As _screenshots_. Code is text, post it as such. But yes, that function lacks any information as to what it might return a promise _of_. – jonrsharpe Jun 22 '21 at 13:30

1 Answers1

-1

There's a difference between any and unknown.

In short for your case - you can't treat unknown as anything, or as Book like you did in your code. If your method returned Promise<any> or Promise<Book> you'd be able to do what you attempted here.

I would go with the latter and annotate the getSingleBook method as such:

getSingleBook(id: number): Promise<Book> {
//...
const potentialBook = data.val();
const book: Book = validateBook(potentialBook); // throw an error if not a book
resolve(book);
//...
}

You can just assert the resolved value as a book if you're 100% sure it is and always will be, but that's ill advised:

getSingleBook(id: number): Promise<Book> {
//...
resolve(book as Book);
//...
}

Thanks jonrsharpe.

EcksDy
  • 1,289
  • 9
  • 25
  • 1
    That just moves the problem around, because the underlying problem is that `getSingleBook` _doesn't_ return `Promise` and `unknown` is still not assignable to `Book`: https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgEIHt0GtkG8C+AsAFAkwCuICYw6IyA5hGBtgBQCUAXMgApToAtsADOEADyssAPjwlkC5FGbko9fkNEQAdMpHoANgDcJlLCHQB3ENLYAiGJjscA3CSLEgA – jonrsharpe Jun 22 '21 at 13:58