无法找到自定义函数参数需要添加的类型

问题描述 投票:0回答:1

我正在使用

tss-react
和 MUI 包,但我无法弄清楚如何为我编写的自定义函数设置
types
,该函数基本上合并了我所有的常见样式和我想要的组件的特定样式。

因此,我在访问我的

classes
对象时遇到 TypeScript 错误。 (例如:
Property 'colorRed' does not exist on type 'Record<never, string>'.

要在

getUseStyles.ts
文件中添加哪些类型,以便我从 commonStyles 文件和组件样式中获取类型? (基本上打字稿/编辑器应该能够在访问
classes
对象键(例如
classes.colorRed
classes.colorBlue
)时进行智能感知)

代码沙盒

// File: Test.tsx
const useStylesHook = getUseStyles(  // Merging component styles and common styles
  (theme) => {
    return {
      colorRed: {
        color: 'red',
      },
      colorBlue: {
        color: 'blue',
      },
    }
})

export default function Test() {
  const { classes, cx } = useStylesHook()
  return (
    <h1 className={cx(classes.colorRed, classes.padding20, classes.colorBlue)}>
      Testing this color
    </h1>
  )
}
// File: commonStyles.ts
export const commonStyles = (theme) => {
  return {
    padding20: {
      paddingTop: '20px',
    },
  }
}
// File: getUseStyles.ts
export const getUseStyles = (
  styles: any, // What types to add here ?
  customStyles?: any,
) => {
  return makeStyles()((theme) => {
    return {
      ...commonStyles(theme),
      ...styles(theme, { ...customStyles }),
    }
  })
}
reactjs typescript material-ui emotion tss
1个回答
0
投票

我们可以通过使传递的

styles
函数返回的记录的键通用来实现此目的,这样推断这些属性所需的信息就不会丢失。

import { Theme } from '@mui/material'
import { CSSObject } from 'tss-react'
import { commonStyles } from '../commonStyles'
import { makeStyles } from './helpers'

export const getUseStyles = <RuleNames extends string>(
  styles: (theme: Theme, customStyles?: any) => Record<RuleNames, CSSObject>, // What types to add here ? (theme: any, customProps: any) => void? not sure
) => {
  return makeStyles()((theme) => {
    return {
      ...commonStyles(theme),
      ...styles(theme),
    }
  })
}

enter image description here

尚不清楚

customStyles
的目的是什么,或者它如何影响传递的
styles
函数的返回值。所以这里基本上没有任何作用。

© www.soinside.com 2019 - 2024. All rights reserved.