I want to use not a dumb mock for CSS modules but real types so I use webpack plugin typings-for-css-modules-loader
for simple css
.foo { color: red; }
.bar { color: green; }
it can generate example.css.d.ts
declaration
export interface ILocals {
'foo': string;
'bar': string;
}
export interface IExampleCss {
locals: ILocals;
'foo': string;
'bar': string;
}
declare const styles: IExampleCss
export default styles;
so in my code I able to use it like so
import css from './example.css';
const { locals } = css;
<div className={locals.foo}>Red</div>
<div className={css.bar}>Green</div>
and VSCode knows that locals.foo and css.bar members
I try to write a function which is able to get any css definitions in typescript as an input parameter
interface IStringHash {
[key: string]: string;
}
interface ICSSLocals {
locals: IStringHash;
[key: string]: string | IStringHash;
}
interface ISomeInterface {
renderComponent: (css: ICSSLocals): React.ReactNode
}
const myFunction = (css: IExampleCss) => {
return (
<div key="1" className={css.locals.foo}>Red</div>
<div key="2" className={css.bar}>Green</div>
)
}
const MyRenderer: ISomeInterface = {
renderComponent: myFunction
^^^^^^^^^^
};
I get the error:
[ts]
Type 'IExampleCss' is not assignable to type 'ICSSLocals'.
Type 'IExampleCss' is not assignable to type 'ICSSLocals'.
Types of property 'locals' are incompatible.
Type 'ILocals' is not assignable to type 'IStringHash'.
Index signature is missing in type 'ILocals'.
What is wrong?
I've wrote a relevant sample in typescript playground
// Declaration with generics
interface IStringHash {
[key: string]: string;
}
interface ICSSModule {
locals: IStringHash;
[key: string]: string | IStringHash;
}
interface returnObject {
a: string,
b: string
}
interface ISomeInterface {
renderComponent: (css: ICSSModule) => returnObject
}
// usage with certain realisation
export interface ILocals {
'foo': string;
'bar': string;
}
export interface IExampleCss {
locals: ILocals;
'foo': string;
'bar': string;
}
const myFunction = (css: IExampleCss): returnObject => {
return {
a: css.locals.foo,
b: css.bar
}
}
const MyRenderer: ISomeInterface = {
renderComponent: myFunction
^^^^^^^
};
here is the error:
[ts]
Type '(css: IExampleCss) => returnObject' is not assignable to type '(css: ICSSModule) => returnObject'.
Types of parameters 'css' and 'css' are incompatible.
Type 'ICSSModule' is not assignable to type 'IExampleCss'.
Property ''foo'' is missing in type 'ICSSModule'.
(property) ISomeInterface.renderComponent: (css: ICSSModule) => returnObject