简体   繁体   中英

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. 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:

  1. Set the type as a Record
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>
  )
}
  1. Make an interface for the state
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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM