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.
2
Answers
Is
word
a string or an object with aword
key whose type is a string?this would be a valid
initialState
:Issues
You’ve typed
searchType
to be an object with aword
property that is a string type.So by declaring the slice state
dictionaryState
type to have a word property that is typesearchType
It’s expecting a value that is an object with a
word
property that is a string type, e.g.You’ve additionally provided incorrect
state.dictionary
value as well. It is typed asdictionary: meaningsType;
but the initial state is an array.Solution
I suspect you really do want
state.word
to be a string, and forstate.dictionary
to be an array ofmeaningsType
objects.The following may also work, basically extending the
searchType
to include the dictionary property (be careful though if thesearchType
type changes):With this typing you’ll be able to use the following
initialState
value: