I have an interface for a book with an optional id (for case a new book which isn't saved yet to server):
interface Book {
id?: string
}
When I fetch all books from backend - I use to create an object byId:
allIds: payload.map(book => book.id!),
where allIds declaration is:
allIds: string[]
as you can see, I added the ! after the book.id in order to specify each book has an Id.
as if I won't do that, Typescript will not compile with:
TS2322: Type '(string | undefined)[]' is not assignable to type 'string[]'.
Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'.
Now, It's working with the !, and I don't expect any book to missing its id, but I would like to find an elegant way to validate it.. just in case.
I can do something like:
allIds: payload.map(book => {
if (!book.id) {
throw new Error("invalid book id")
}
return book.id
}),
but I would like to know if you have any idea for a nicer one-liner elegant solution to validate the items while mapping it.
iddoesn't exist in theBookelement?