Quramy / typed-css-modules

Creates .d.ts files from CSS Modules .css files
MIT License
1.05k stars 69 forks source link

Extended types in generated `.d.ts` files #31

Open pmyagkov opened 7 years ago

pmyagkov commented 7 years ago

Issue

Right now it's impossible to get a styles value using an indexer:

/**
  * a css file
  */

.root {}
.dark {}
.light {}
/**
  * a ts file using the declared styles
  */

import * a styles from './styles.css'
import * as cn from 'classnames'
...
type Theme = 'dark' | 'light'
const theme: Theme = 'dark'

// this doesn't work
const className = cn(styles.root, {
  [styles[theme]]: true,
})

// this works
const className = cn(styles.root, {
  [styles.dark]: theme === 'dark',
  [styles.light]: theme === 'light',
})

The first snippet doesn't work because of an error:

ERROR in ./src/components/atoms/Component.tsx (22,12): error TS7017: Element implicitly has an 'any' type because type 'typeof "/Users/puelle/Projects/test/style_typings/atoms/Component.css"' has no index signature.

Possible resolution

To generate kind of extended styles typings:

/**
  * a generated .d.ts file
  */

interface FilenameStyles {
  dark: string;
  light: string;
}

const typedStyles: Record<keyof FilenameStyles, string> = styles
// to preserve `import * as styles from ...` behaviour
export = typedStyles
// to create a default export (`import styles from ...`)
export default typedStyles
pmyagkov commented 7 years ago

@Quramy could you comment this please?

Quramy commented 7 years ago

@pmyagkov I'm attempting to reproduce your error TS7017, but I can't...

/* a.ts */
import * as cn from 'classnames';
import * as styles from "./styles.css";

type Theme = 'dark' | 'light';
// type Theme = keyof typeof styles; // It works too.

const theme: Theme = 'dark';

const className = cn(styles.dark, {
  [styles[theme]]: true,
});
/* styles.css.d.ts [generated by tcm] */
export const dark: string;
export const light: string;

And my tsconfig.json is :

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "strict": true
  }
}

There is no compilation error. Would you tell me a reproducing repository?

pmyagkov commented 7 years ago

I'll provide a minimal reproducible demo in a mean time.

dimensi commented 4 years ago

I have same problem. изображение