Skip to content

Commit

Permalink
[typescript] Illustrate issue with ambiguous css class names (#12724)
Browse files Browse the repository at this point in the history
* [typescript] Illustrate issue with ambiguous css class names

* small edits
  • Loading branch information
eps1lon authored and oliviertassinari committed Aug 31, 2018
1 parent 2d954e3 commit cd8ec88
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 0 deletions.
46 changes: 46 additions & 0 deletions docs/src/pages/guides/typescript/typescript.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,52 @@ const styles = ({ palette, spacing }: Theme) => createStyles({

`createStyles` is just the identity function; it doesn't "do anything" at runtime, just helps guide type inference at compile time.

### Media queries

`withStyles` allows a styles object with top level media-queries like so:

```ts
const styles = createStyles({
root: {
minHeight: '100vh',
},
'@media (min-width: 960px)': {
root: {
display: 'flex',
},
},
});
```

However to allow these styles to pass TypeScript the definitions have to be ambiguous concerning names for CSS classes and actual CSS property names. Due to this class names that are equal to CSS properties should be avoided.

```ts
// error because TypeScript thinks `@media (min-width: 960px)` is a class name
// and `content` is the css property
const ambiguousStyles = createStyles({
content: {
minHeight: '100vh',
},
'@media (min-width: 960px)': {
content: {
display: 'flex',
},
},
});

// works just fine
const ambiguousStyles = createStyles({
contentClass: {
minHeight: '100vh',
},
'@media (min-width: 960px)': {
contentClass: {
display: 'flex',
},
},
});
```

### Augmenting your props using `WithStyles`

Since a component decorated with `withStyles(styles)` gets a special `classes` prop injected, you will want to define its props accordingly:
Expand Down
29 changes: 29 additions & 0 deletions packages/material-ui/test/typescript/styles.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,35 @@ withStyles(theme =>
}),
);

{
// allow top level media queries
// https://github.com/mui-org/material-ui/issues/12277

// typescript thinks `content` is the CSS property not a classname
// $ExpectError
const ambiguousStyles = createStyles({
content: {
minHeight: '100vh',
},
'@media (min-width: 960px)': {
content: {
display: 'flex',
},
},
});

const styles = createStyles({
contentClass: {
minHeight: '100vh',
},
'@media (min-width: 960px)': {
contentClass: {
display: 'flex',
},
},
});
}

{
const styles = (theme: Theme) =>
createStyles({
Expand Down

0 comments on commit cd8ec88

Please sign in to comment.