TypeScript 似乎将变量视为 'any',即使它已定义

TypeScript seems to be seeing a variable as 'any' even though it's defined

我有以下组件:

import React from 'react';
import classNames from 'classnames';

import styles from './styles.module.scss';

const cx = classNames.bind(styles);

interface Props {
  /**
   * Allows a user to apply a custom class
   */
  className?: string;
  /**
   * The content to show in the button
   */
  children: ReactNode;
  /**
   * The if you want to include an icon, this specifies the side of the button the icon should appear on
   */
  alignIcon?: 'left' | 'right';
  /**
   * The event action to fire when the button is clicked
   */
  onClick?: (fn) => void;
}


/* Render component */
export const Button = React.forwardRef<HTMLButtonElement, Props>(
  ({ alignIcon, className, onClick, children }: Props, ref) => (
    <button
      ref={ref}
      className={cx(
        styles['button'],
        alignIcon && styles[`icon-${alignIcon}`],
        className
      )}
      onClick={onClick}
    >
      {children}
    </button>
  )
);

Button.displayName = 'Button';

export default Button;

它完全按照我想要的方式工作,但是当我 运行 tsc

时出现以下错误
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'CssExports'.
  No index signature with a parameter of type 'string' was found on type 

似乎不​​喜欢使用变量,就好像我用 styles['icon-left']styles['icon-right'] 替换 styles[`icon-${alignIcon}`] 一样,错误消失了。我不确定隐含的 any 是从哪里来的。

此外,这是生成的 styles.modules.scss.d.ts 文件,其中包含 CssExports

interface CssExports {
  'button': string;
  'error': string;
  'icon': string;
  'icon-left': string;
  'icon-none': string;
  'icon-right': string;
}
export const cssExports: CssExports;
export default cssExports;

您可以尝试显式转换变量:styles[`icon-${alignIcon}`] as CssExports.

或者,您可以通过将以下内容添加到 tsconfig.json compilerOptions 来抑制此错误:

compilerOptions: {
  "suppressImplicitAnyIndexErrors": true,
}

您的 alignIcon 参数似乎是可选的,因此它可能为空。确保通过在此处设置一些默认值来处理这种情况:

export const Button = ({ alignIcon = "left", className, onClick, children }: Props, ref) => {
    /* element body */
})

我在其他组件中也遇到了问题,所以我 'resolved' 通过向项目添加通用 scss-modules.d.ts 文件并删除所有特定文件来解决问题。如果有人感兴趣,该文件如下所示:

declare module "*.scss" {
  const styles: { [className: string]: string };     
  export default styles; 
}