简体   繁体   English

在 React TypeScript 中仅包含 boolean 值的 object 的类型是什么?

[英]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:有两种方法:

  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为 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:)否则奥列格上面的回答应该这样做:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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