Pull out property of computed value: TypeScript Error
Standupic opened this issue · comments
interface IBook { id: string tittle: string ... }
const model = { currentBook?: Computed<Books, IBook | undefined, IBook>; }
currentBook: computed((state) => state.books.find((book) => book.id === state.id))
const Component => {
currentBook?.id // **TypeScript Error Property 'id' does not exist on type 'Computed '.**
currentBook?.title // **TypeScript Error Property 'title' does not exist on type 'Computed '.**
currentBook?.result?.id // undefined
}
@ts-ignore
const { publisher, synopsis, title, author, pageCount, id, coverImageUrl } = currentBook; // WORKS
@Standupic see this known issue, it may be related to your problem: https://easy-peasy.dev/docs/known-issues/typescript-optional-computed-properties.html
Also, it looks like you may be using the Computed<T, U, V>
generic type incorrectly? The third param you're providing seems incorrect. The types the Computed
props expects correspond to local model, result, and store model:
export type Computed<
Model extends object,
Result,
StoreModel extends object = {}
> = {
type: 'computed';
result: Result;
};
@Standupic Just change this line:
const model = { currentBook?: Computed<Books, IBook | undefined, IBook>; }
into this:
const model = { currentBook?: Computed<Books, IBook | undefined>; }
as @no-stack-dub-sack mentioned.
@jacekk @no-stack-dub-sack unfortunately no one of provided suggestions do not work properly.
export interface Books {
currentBook?: Computed<Books, IBook | undefined>;
}
const book: Books = {
currentBook: computed((state) => state.books.find((book) => book.id === state.id))
}
Books.currentBook?: Computed<Books, IBook | undefined, {}> | undefined
const currentBook = useStoreState((state: StoreModel) => state.books.currentBook);
const { publisher, synopsis, title, author, pageCount, id, coverImageUrl } = currentBook;
}
Property 'pageCount' does not exist on type 'Computed | undefined'. // so on so foth.
@Standupic First of all, I cannot see IBook
definition, it might be missing this very property. But...
please remember that currentBook
is of type IBook
or undefined
. You need to checked whether this computed value is actually "Truthy". After const currentBook = ...
just check whether this is an object or not.
@Standupic I can see the property --> https://github.com/Standupic/Book-discovery/blob/main/src/types/books.ts#L8 😉
So just add a check in your Book
component.
@jacekk It works properly, thanks for your time.
const currentBook = useStoreState((state: StoreModel) => state.books.currentBook);
if (currentBook && currentBook.result) {
const { publisher, synopsis, title, author, pageCount, id, coverImageUrl } = currentBook.result;