[英]What is the type for an object that contains only boolean values in React TypeScript?
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.我有一些我在 React JavaScript 中编写的代码,现在已经迁移到 TypeScript 并且我不完全确定将类型声明为什么。 I preferably don't want to use the type
any
:我最好不想使用
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:)否则奥列格上面的回答应该这样做:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.