Home > Software engineering >  In Redux Toolkit, TypeScript doesn't catch the wrong type of state
In Redux Toolkit, TypeScript doesn't catch the wrong type of state

Time:05-19

import { createSlice, PayloadAction } from '@reduxjs/toolkit';

interface InfoState {
    name : string
    age : number
    email : string
}

const initialState = { name: '', age: 0, email: '' } as InfoState 

const userSlice = createSlice({
    name: 'user',   
    initialState: { value: initialState },
    reducers: {        
        login(state, action: PayloadAction<InfoState>) {
            console.log(typeof(action.payload.age));
            state.value = action.payload
        },
        logout(state) {
            state.value = { name: '', age: 0, email: ''  }
        },
    },
})

export const { login } = userSlice.actions
export const { logout } = userSlice.actions
export default userSlice.reducer

There is a file of typescript from the Redux Toolkit.

dispatch(login({ name: 123, age: "20", email: "[email protected]" }))

I have dispatched the following values ​​in javascript

It is different from the type set in TypeScript, but the state is changed. I want to know why.

CodePudding user response:

TypeScript only exists in your editor to tell you where you are doing wrong. In your browser - or JavaScript for that matter - TypeScript annotations have no meaning. TypeScript will not stop you at runtime from doing something stupid, none of your TypeScript annotations exist in the user's browser any more.

If you want to have run-time-checking, you have to write that by hand. That's neither TypeScript's job not Redux-Toolkit's job.

  • Related