Home > front end >  When using typescript in redux, questions related to initialization of initialstate
When using typescript in redux, questions related to initialization of initialstate

Time:11-02

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:

  1. You've used the name Books, not books.
  2. It's a property, not a variable.
  3. You've given the type Book to initialState, but the properties you're initializing it with don't match the properties the Book type defines.
  4. 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[],
};
  • Related