Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
81 views
in Technique[技术] by (71.8m points)

javascript - 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
  });
question from:https://stackoverflow.com/questions/65919903/what-is-the-type-for-an-object-that-contains-only-boolean-values-in-react-typesc

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>
  )
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...