简体   繁体   English

三元运算符 typescript 在反应真值时出错 state

[英]ternary operator typescript has error when true value is react state

I am trying to implement sorting on a table and am getting an error of:我正在尝试对表格进行排序,但出现以下错误:

(property) direction?: "asc" | "desc"
No overload matches this call.
  Overload 1 of 3, '(props: { href: string; } & { active?: boolean; direction?: "asc" | "desc"; hideSortIcon?: boolean; IconComponent?: ComponentType<{ className: string; }>; } & { action?: Ref<ButtonBaseActions>; ... 10 more ...; TouchRippleProps?: Partial<...>; } & CommonProps<...> & Pick<...>): Element', gave the following error.
    Type 'string' is not assignable to type '"asc" | "desc"'.
  Overload 2 of 3, '(props: { component: ElementType<any>; } & { active?: boolean; direction?: "asc" | "desc"; hideSortIcon?: boolean; IconComponent?: ComponentType<{ className: string; }>; } & { ...; } & CommonProps<...> & Pick<...>): Element', gave the following error.
    Type 'string' is not assignable to type '"asc" | "desc"'.
  Overload 3 of 3, '(props: DefaultComponentProps<ExtendButtonBaseTypeMap<TableSortLabelTypeMap<{}, "span">>>): Element', gave the following error.
    Type 'string' is not assignable to type '"asc" | "desc"'.ts(2769)
import {
  Badge,
  Box,
  Drawer,
  IconButton,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableSortLabel,
  TableHead,
  TableRow,
  Tooltip
} from "@material-ui/core";
import { useEffect, useState } from "react";

function TeamsTableImpl({
  a
}: {
  a:number
}) {
  const [orderDirection, setOrderDirection] = useState('asc')
  const [valueToOrderBy, setValueToOrderBy] = useState('team')


  const handleRequestSort = (event: any, property: any) => {
    const isAscending = (valueToOrderBy === property && orderDirection === 'asc')
    setValueToOrderBy(property)
    setOrderDirection(isAscending ? 'desc' : 'asc')
  }
  

  const createSortHandler = (property: any) => (event: any) => {
    handleRequestSort(event, property)
  }

  console.log(orderDirection);
  console.log(typeof(orderDirection));
  const myorderDirection = "desc";
  console.log(typeof(myorderDirection))


  return (
    <Box>
      <TableContainer style={{ marginTop: 32 }}>
        <Table>
          <TableHead>
            <TableRow>

              <TableCell>
              Team
                <TableSortLabel 
                  active={valueToOrderBy === "team"}
                  // for some reason when orderDirection is passed as a state, this does not compile, even
                  // though the state value is a string that says 'desc' or 'asc', but if you hard code 
                  // a string in the ternary operator, even if it shows the same value and type, it works correctly.
                  // need to investigate further.

                  direction = { valueToOrderBy === 'team' ? orderDirection : 'asc' }
                  onClick={createSortHandler("team")}>
                    Team
                </TableSortLabel>
              </TableCell>
            </TableRow>
          </TableHead>
        </Table>
      </TableContainer> 
    </Box>
  );
}

As stated in the code, if orderDirection is passed as a state the error above shows, I have verified that the typeof(orderDirection) is a string.如代码中所述,如果 orderDirection 作为 state 传递,则上面的错误显示,我已经验证 typeof(orderDirection) 是一个字符串。 When I set a new variable called myorderDirection to the same string that the state orderDirection is, it works, it just does not work when the state is passed.当我将一个名为 myorderDirection 的新变量设置为与 state orderDirection 相同的字符串时,它可以工作,但在传递 state 时它就不起作用。

I am out of ideas why this might be.我不知道为什么会这样。

Here are the versions of react and material-ui I am using.这是我正在使用的 react 和 material-ui 的版本。

"@material-ui/core": "^4.11.3",
"react": "^17.0.1"

Just enforce the type of your state: useState<'asc'|'desc'>('asc') .只需强制执行 state 的类型: useState<'asc'|'desc'>('asc') This way orderDirection will be 'asc'|'desc' instead of the infered string .这样orderDirection将是'asc'|'desc'而不是推断的string

const [orderDirection, setOrderDirection] = useState<any>('asc')

or

const [orderDirection, setOrderDirection] = useState<'asc'|'desc'>('asc')

this would work这会工作

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

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