【发布时间】:2022-01-10 20:12:08
【问题描述】:
对于对象中处理函数的以下代码(请参阅Playground Link),我使用 Record 类型:
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
};
}
};
我确实收到了处理函数的以下错误:
TS2322: Type '(state: State, action: InitializeAction) => State' is not assignable to type '(state: State, action: Action) => State'.
Types of parameters 'action' and 'action' are incompatible.
Type 'Action' is not assignable to type 'InitializeAction'.
Type 'LoginAction' is not assignable to type 'InitializeAction'.
Types of property 'type' are incompatible.
Type '"LOGIN"' is not assignable to type '"INITIALIZE"'.
【问题讨论】:
-
拜托,看看我不久前写的the guide to type-safe Redux actions,可能值得花时间
-
看看typescript union这是一个常见问题;)
标签: typescript react-typescript