Проблемы с Emotion Js и TypeScript при передаче реквизитов в стилизованные - PullRequest
1 голос
/ 24 апреля 2020

я получил эти ошибки:

No overload matches this call.   Overload 1 of 2, '(...styles: Interpolation<Pick<DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>, "form" | ... 264 more ... | "value"> & { ...; }>[]): StyledComponent<...>', gave the following error.
    Argument of type 'TemplateStringsArray' is not assignable to parameter of type 'Interpolation<Pick<DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>, "form" | ... 264 more ... | "value"> & { ...; }>'.
      Type 'TemplateStringsArray' is not assignable to type 'ObjectInterpolation<Pick<DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>, "form" | ... 264 more ... | "value"> & { ...; }>'.
        Types of property 'filter' are incompatible.
          Type '{ <S extends string>(callbackfn: (value: string, index: number, array: readonly string[]) => value is S, thisArg?: any): S[]; (callbackfn: (value: string, index: number, array: readonly string[]) => unknown, thisArg?: any): string[]; }' is not assignable to type 'string | string[] | undefined'.
            Type '{ <S extends string>(callbackfn: (value: string, index: number, array: readonly string[]) => value is S, thisArg?: any): S[]; (callbackfn: (value: string, index: number, array: readonly string[]) => unknown, thisArg?: any): string[]; }' is missing the following properties from type 'string[]': pop, push, concat, join, and 27 more.   Overload 2 of 2, '(template: TemplateStringsArray, ...styles: Interpolation<Pick<DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>, "form" | ... 264 more ... | "value"> & { ...; }>[]): StyledComponent<...>', gave the following error.
    Argument of type '(props: HamburguerProps) => "250px" | "0"' is not assignable to parameter of type 'Interpolation<Pick<DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>, "form" | ... 264 more ... | "value"> & { ...; }>'.
      Type '(props: HamburguerProps) => "250px" | "0"' is not assignable to type 'FunctionInterpolation<Pick<DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>, "form" | ... 264 more ... | "value"> & { ...; }>'.
        Types of parameters 'props' and 'mergedProps' are incompatible.
          Property 'open' is missing in type 'Pick<DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>, "form" | ... 264 more ... | "value"> & { ...; }' but required in type 'HamburguerProps'.  TS2769

по этому коду:

> 25 | export const Hamburguer = styled('button')`
       |                           ^
    26 |   position: absolute;
    27 |   left: ${(props: HamburguerProps) => (props.open ? '250px' : '0')};
    28 | `;

Я думал, что проблема была связана с моим кодом, но я думаю, что все тесты я выполняю это не так

Я искал эту ошибку или решения и не нашел

my TsConfig

{
  "compilerOptions": {
    "target": "es5",
    "types": ["node", "@emotion/core"],
    "lib": ["dom", "dom.iterable", "esnext"],
    "baseUrl": "src",
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react"
  },
  "include": ["src"]
}

my Код TSX:

import Logo from 'assets/images/Logo.png';
import { useSelector, useDispatch } from 'react-redux';
import { toggleSide } from 'redux/slices/sideBar';

interface RootState {
  sideBarStatus: boolean;
}

interface SideBar {
  isOpen: boolean;
}

const LogoNavigation: React.FC<SideBar> = ({ isOpen }) => {
  const dispatch = useDispatch();
  return (
    <LogoSide>
      <img src={Logo} alt="Logo Elo Ghost" />
      <Hamburguer open={isOpen} onClick={() => dispatch(toggleSide(!isOpen))}>
        <div />
        <div />
        <div />
      </Hamburguer>
    </LogoSide>
  );
};

const SideNavigation: React.FC = () => {
  // const { sideIsOpen } = useSelector((RootState) => RootState.toggleSide);
  const selectIsOpen = (state: RootState) => state.sideBarStatus;
  const sideBarStatus = useSelector(selectIsOpen);
  return (
    <SideNav>
      <LogoNavigation isOpen={sideBarStatus} />
    </SideNav>
  );
};

export default SideNavigation;

Мои стили с эмоциями

import styled from '@emotion/styled';

type HamburguerProps = {
  open: boolean;
};

export const SideNav = styled('nav')`
  max-width: 250px;
  width: 100%;
  height: 100vh;
  background: #437fb9;
`;

export const LogoSide = styled('div')`
  display: flex;
  justify-content: space-between;
  width: 100%;
  height: 60px;
  background: #fdca40;
  img {
    height: 50px;
  }
`;

export const Hamburguer = styled('button')`
  position: absolute;
  left: ${(props: HamburguerProps) => (props.open ? '250px' : '0')};
`;

и здесь у меня есть GIF, где я рендерил свой компонент, но сразу после появляется ошибка

enter image description here

1 Ответ

1 голос
/ 25 апреля 2020

Когда вы работаете с библиотеками JSS (такими как Emotion и Styled Components) и TypeScript, чтобы заставить props работать, вы должны будете предоставить обобщение, которое задает типизацию. Это может быть сделано с использованием интерфейсов или псевдонимов типов.

В вашем случае вам нужно будет указать c, что у Hamburger есть HamburguerProps с помощью styled<HamburguerProps>:

export const Hamburguer = styled.button<HamburguerProps>`
  position: absolute;
  left: ${(props) => (props.open ? '250px' : '0')};
`;
...