When utilizing handler functions within an object, the Record type is used in the following code snippet:
interface User {
id: string;
avatar: string;
email: string;
name: string;
role?: string;
[key: string]: any;
}
interface State {
isInitialized: boolean;
isAuthenticated: boolean;
user: User | null;
}
type InitializeAction = {
type: 'INITIALIZE';
payload: {
isAuthenticated: boolean;
user: User | null;
};
};
type LoginAction = {
type: 'LOGIN';
payload: {
user: User;
isAuthenticated: boolean;
};
};
type LogoutAction = {
type: 'LOGOUT';
};
type RegisterAction = {
type: 'REGISTER';
payload: {
user: User;
};
};
type Action =
| InitializeAction
| LoginAction
| LogoutAction
| RegisterAction;
const handlers: Record<string, (state: State, action: Action) => State> = {
INITIALIZE: (state: State, action: InitializeAction): State => {
const {
isAuthenticated,
user
} = action.payload;
return {
...state,
isAuthenticated,
isInitialized: true,
user
};
},
LOGIN: (state: State, action: LoginAction): State => {
const { user } = action.payload;
return {
...state,
isAuthenticated: true,
user
};
},
LOGOUT: (state: State): State => ({
...state,
isAuthenticated: false,
user: null
}),
REGISTER: (state: State, action: RegisterAction): State => {
const { user } = action.payload;
return {
...state,
isAuthenticated: true,
user
};
}
};
An error occurs when trying to use the handler functions:
TS2322: Type '(state: State, action: InitializeAction) => State' is not assignable to type '(state: State, action: Action) => State'.
Types of parameters 'action' and 'action' conflict.
Type 'Action' does not match 'InitializeAction'.
Type 'LoginAction' cannot be assigned to 'InitializeAction'.
Conflicting types in property 'type'.
'Type "LOGIN"' is not the same as 'Type "INITIALIZE"'.