export interface Book{
title : String,
contents: String,
thumbnail: String,
liked: boolean
}
const initialState : Book = {
Books : Book[],
likedBook: Book[]
};
I have created a variable called books with type Book. But it didn't work. What's the problem? Thanks for explaining why
CodePudding user response:
There are a couple of issues there:
- You've used the name
Books
, notbooks
. - It's a property, not a variable.
- You've given the type
Book
toinitialState
, but the properties you're initializing it with don't match the properties theBook
type defines. Book[]
is not how you create an empty array in JavaScript/TypeScript. It's just[]
. The type comes from the type declaration, if any, of the variable/property you're assigning it too.
I think you may have wanted this:
export interface Book{
title : String,
contents: String,
thumbnail: String,
liked: boolean
}
// An iterface/type to use for `initialState` (you could also define it in line)
interface State {
books: Book[];
likedBooks: Book[]; // I've changed this to the plural, since it's an array
}
const initialState : State = {
books: [],
likedBooks: [],
};
or if you don't want to define the State
type, you can do it inline in a couple of ways when defining initialState
:
const initialState: {books: Book[]; likedBook: Book[];} = {
books: [],
likedBooks: [],
};
// Or
const initialState = {
books: [] as Book[],
likedBooks: [] as Book[],
};