I have some code that I wrote in React JavaScript that has now been migrated over to TypeScript and I'm not entirely sure what to declare the type as. I preferably don't want to use the type any
:
const [responseStatus, setResponseStatus] = React.useState<any>({
emptyResponse: true,
unsuccessfulResponse: false,
successfulResponse: false,
badResponse: false
});
There are two ways:
type ResponseType = Record<string, boolean>;
const Component: React.FC = (): JSX.Element => {
const [responseStatus, setResponseStatus] = React.useState<ResponseType>({
emptyResponse: true,
unsuccessfulResponse: false,
successfulResponse: false,
badResponse: false
});
return (
<div>{responseStatus.emptyResponse}</div>
)
}
interface ResponseStatus {
[key: string]: boolean;
}
const Component: React.FC = (): JSX.Element => {
const [responseStatus, setResponseStatus] = React.useState<ResponseStatus>({
emptyResponse: true,
unsuccessfulResponse: false,
successfulResponse: false,
badResponse: false
});
return (
<div>{responseStatus.emptyResponse}</div>
)
}
If you want to be very specific:
interface ResponseStatus {
[key: 'emptyResponse' | 'unsuccessfulResponse' | 'successfulResponse' | 'badResponse' ]: boolean;
}
Otherwise Oleg's answer above should do it:)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.