I'm having a fair amount of issues with this file migration to typescript, so overall would appreciate any feedback on what could be improved to make this more type safe and less redundant possibly. This is the code block I am working with:
import React, { useEffect, useState } from 'react'
import axios from 'axios'
interface iProps {
repoName: string
}
interface iCommits {
[index: string]: iCommit[],
}
interface iCommit {
sha: string,
commit: iCommitData
}
interface iCommitData {
author: iAuthor
message: string
}
interface iAuthor {
name: string,
email: string,
date: number
}
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
const CommitList = (props: iProps) => {
const repoName = props.repoName
const [commitList, setCommitList] = useState<iCommits | []>([])
useEffect(() => {
axios
.get(`https://api.github.com/repos/mathiusjohnson/${repoName}/commits`)
.then(res => {
setCommitList(res.data)
})
}, [repoName])
const commitKeys = Object.keys(commitList)
console.log(commitList[commitKeys[0] as keyof iCommits]);
const renderedCommits = commitKeys !== undefined && commitKeys.length > 0
? (commitKeys as string[]).map((commit: string, index: number) => {
if (index !== 0) {
return null
} else {
const startTimeISOString = commitList[commit as keyof iCommits].commit.author.date
const startTimeDate = new Date(startTimeISOString).toDateString()
console.log("latest commit: ", startTimeDate);
return (
<li key={index}>
<p>Author: {commitList[commit].commit.author.name}</p>
<p>Committed on: {startTimeDate}</p>
<p>Commit message: {sortedCommits[commit].commit.message}</p>
</li>
)
}
})
: ''
return (
<div>
<h2>Most recent commit</h2>
<ol>{renderedCommits}</ol>
</div>
)
}
export default CommitList
You can test the axios call out if you need to with this url (not related to this current project, just the first one I thought of to share that is not private):
https://api.github.com/repos/mathiusjohnson/social_network_api/commits
My issue right now I'm getting is this error:
Element implicitly has an 'any' type because expression of type 'string | number' can't be used to index type '[] | iCommits'.
No index signature with a parameter of type 'string' was found on type '[] | iCommits'.ts(7053)
On any code that I'm trying to use a key in the commitList in code block below, like this console.log:
console.log(commitList[commitKeys[0] as keyof iCommits]);
Again, any overall feedback for improvement is greatly appreciated. Thanks in advance!
question from:
https://stackoverflow.com/questions/65892472/no-index-signature-with-a-parameter-of-type-string-was-found-on-type-ico 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…