如何使用css-modules-loaders键入和使用索引属性

我正在使用Types-for-css-modules-loader为我的CSS模块生成打字稿。总的来说,它运作良好。我有一个这样的导入语句:

import * as styles from './MyStyles.scss'

然后我可以像这样在我的JSX中使用它:

<div classname={styles.cardBody}>

太好了!我有一种情况,我想将字符串传递给函数并索引可用样式。像这样:

const getStyle = (styleName: string) => {
        return `otherClass1 otherClass2 ${styles[styleName]}`
    }

打字稿对此不满意:

${styles[styleName]}

它抱怨:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof import("<path to scss file>")'.
  No index signature with a parameter of type 'string' was found on type 'typeof import("<path to scss file>")'.

如果不使用ts-ignore,如何使打字稿快乐?假设没有更好的方法,如果我不得不以某种方式强制转换(我不确定该怎么做),我会失去一些类型安全性。

谢谢!

sgdtiancai 回答:如何使用css-modules-loaders键入和使用索引属性

不幸的是,我不知道如何避免这种行为。即使这个简单的代码也会返回您的错误:

const styles = {style_main: 'fgsfds'}
const styleName = 'main'
console.log(styles[`style_${styleName}`])

console.log(styles['style_main'])工作正常。

作为潜在危险的解决方法,您可以在tsconfig.json中使用"suppressImplicitAnyIndexErrors": true来全局禁用此检查。

本文链接:https://www.f2er.com/3155011.html

大家都在问