カスタム応答データオブジェクトから[key、value]ペアを返そうとしていますが、各key [value]をループしようとすると、次のエラーが発生します。
No index signature with a parameter of type 'string' was found on type 'IResponse'
または
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'IResponse'
これが私のDetail.tsxです:
interface IResponse {
birth_year: string;
created: string;
edited: string;
eye_color: string;
films: string[];
gender: string;
hair_color: string;
heigth: string;
homeworld: string;
mass: string;
name: string;
skin_color: string;
species: string[];
startships: string[];
url: string;
vehicles: string[];
}
const Detail = () => {
const [person, setPerson] = useState<IResponse>({} as IResponse);
const { id } = useParams();
useEffect(() => {
api.get(`people/${id}`).then((res) => {
if (res.data) setPerson(res.data as IResponse);
});
}, [id]);
function printValues() {
return Object.keys(person).map((key) => (
<li>
{key}:{person[key]}
</li>
));
}
return <ul>{printValues()}</ul>;
};
私の質問は:なぜこのコード:
function objectEntries() {
const a = "name";
const entries = person[a];
console.log(entries);
}
objectEntries();
正常に動作し、printValues関数では動作しませんか?
オブジェクトが[key:string]:value:anyにIResponseインターフェイスでアクセスできることをTypeScriptに伝える必要があるだけです!
お気に入り:
interface IResponse {
[key: string]: your-value-type
[...]
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加