I did this dictionary project fine using Props. Now I am trying to do in redux-toolkit.
I have types in a separate file
export type searchType = {
word: string;
}
export type meaningsType = {
word: string;
phonetic: string;
phonetics:[text: string, audio: string];
meanings:[
{
partOfSpeech: string;
definitions:[
{
definition: string;
synonyms: string[];
antonyms: string[];
}
];
}
];
license: {
name: string;
url: string;
};
sourceUrls: string;
};
I import this into a dictionarySlice.ts file
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { searchType, meaningsType } from "../../types/dictionary";;
export type dictionaryState = {
word: searchType;
dictionary: meaningsType;
}
const initialState: dictionaryState = {
word: '',
dictionary: [],
}
export const dictionarySlice = createSlice({
name: 'dictionary',
initialState,
reducers: {
}
})
How can I pass more than one type when creating initialState? Because in my example for value of initialState of word complains with error:
Type 'string' is not assignable to type 'searchType'.ts(2322) dictionarySlice.ts(5, 3): The expected type comes from property 'word' which is declared here on type 'dictionaryState' (property) word: searchType
Getting similar error for value of initialState of dictionary. I cannot go further defining reducers until this error is solved.
You've typed searchType
to be an object with a word
property that is a string type.
export type searchType = {
word: string;
}
So by declaring the slice state dictionaryState
type to have a word property that is type searchType
export type dictionaryState = {
word: searchType;
dictionary: meaningsType;
}
It's expecting a value that is an object with a word
property that is a string type, e.g.
const initialState: dictionaryState = {
word: { word: '' },
...
}
You've additionally provided incorrect state.dictionary
value as well. It is typed as dictionary: meaningsType;
but the initial state is an array.
I suspect you really do want state.word
to be a string, and for state.dictionary
to be an array of meaningsType
objects.
export type dictionaryState = {
word: string;
dictionary: meaningsType[];
}
The following may also work, basically extending the searchType
to include the dictionary property (be careful though if the searchType
type changes):
export type dictionaryState = searchType & {
dictionary: meaningsType[];
}
With this typing you'll be able to use the following initialState
value:
const initialState: dictionaryState = {
word: '', // <-- string
dictionary: [], // <-- meaningsType[]
}