【发布时间】:2021-12-31 16:15:17
【问题描述】:
我在 thread 上关注 Guilherme 提供的 TypeScript 示例(粘贴在下面)。
但我收到一个错误:Element 隐式具有“任何”类型,因为表达式类型为“字符串 |”。号码 |符号'不能用于索引类型'IState'。
在 'IState'.ts(7053) 类型上没有找到带有 'string' 类型参数的索引签名
关注this我尝试添加的文章:
const result: IState = { ...state };
result[action.type as keyof IState] = action.value;
return result;
但这并不能解决问题。这样的问题有很多回答,但我错过了一些东西。
import React, { FC, Reducer, useReducer } from "react";
interface IState {
email: string;
password: string;
passwordConfirmation: string;
username: string;
}
interface IAction {
type: string;
value?: string;
}
const initialState: IState = {
email: "",
password: "",
passwordConfirmation: "",
username: "",
};
const reducer = (state: IState, action: IAction) => {
if (action.type === "reset") {
return initialState;
}
const result: IState = { ...state };
result[action.type] = action.value;
return result;
};
export const Signup: FC = props => {
const [state, dispatch] = useReducer<Reducer<IState, IAction>, IState>(reducer, initialState, () => initialState);
const { username, email, password, passwordConfirmation } = state;
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
/* fetch api */
/* clear state */
dispatch({ type: "reset" });
};
const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const { name, value } = e.target;
dispatch({ type: name, value });
};
return (
<form onSubmit={handleSubmit}>
<div>
<label>
Username:
<input value={username} name="username" onChange={onChange} />
</label>
</div>
<div>
<label>
Email:
<input value={email} name="email" onChange={onChange} />
</label>
</div>
<div>
<label>
Password:
<input
value={password}
name="password"
type="password"
onChange={onChange}
/>
</label>
</div>
<div>
<label>
Confirm Password:
<input
value={passwordConfirmation}
name="passwordConfirmation"
type="password"
onChange={onChange}
/>
</label>
</div>
<button>Submit</button>
</form>
);
};
【问题讨论】:
标签: typescript