Skip to content

Commit

Permalink
Update/correct TypeScript docs to reflect current best practice (#2598)
Browse files Browse the repository at this point in the history
* Update/correct TypeScript docs to reflect current best practice

#2596

* Clean up typescript.mdx per Andarist's suggestions

* Add back deleted section to typescript.mdx
  • Loading branch information
srmagura committed Dec 22, 2021
1 parent e442f44 commit 2790dc9
Showing 1 changed file with 35 additions and 57 deletions.
92 changes: 35 additions & 57 deletions docs/typescript.mdx
Expand Up @@ -2,10 +2,19 @@
title: 'TypeScript'
---

Emotion includes TypeScript definitions for `@emotion/react` and `@emotion/styled`. These definitions also infer types for css properties with the object syntax, HTML/SVG tag names, and prop types.
Emotion includes TypeScript definitions for `@emotion/react` and `@emotion/styled`. These definitions infer types for css properties with the object syntax, HTML/SVG tag names, and prop types.

## @emotion/react

The easiest way to use the css prop with TypeScript is with the new JSX transform and the `jsxImportSource` TSConfig option (available since TS 4.1). For this approach, your TSConfig `compilerOptions` should contain

```json
"jsx": "react-jsx",
"jsxImportSource": "@emotion/react"
```

For most users, this is all the setup that is required. You can now define styles using the object syntax or template literal syntax and pass them to your components via the `css` prop.

```tsx
import { css } from '@emotion/react'

Expand All @@ -22,7 +31,7 @@ const subtitleStyle = css`
`
```

TypeScript checks css properties with the object style syntax using [csstype](https://www.npmjs.com/package/csstype) package, so following code will emit errors.
Object styles are recommended since they are type checked with the help of the [csstype](https://www.npmjs.com/package/csstype) package. For example, the following code will emit an error.

```tsx
import { css } from '@emotion/react';
Expand All @@ -35,47 +44,41 @@ const titleStyle = css({
});
```

To make the css prop work with pure TypeScript (without babel plugin) you need to add `/** @jsx jsx */` at the top of every file that is using the css prop:
When using our JSX factory, TypeScript only allows the `css` prop on components that accept a `className` prop. This is because `@emotion/react` resolves the value of the `css` prop to a class name and then passes this class name down to the rendered component.

### With the Babel plugin

[`@emotion/babel-plugin`](/docs/babel) is completely optional for TypeScript users. If you are not already using Babel, you probably shouldn't add it to your build tooling unless you truly need one of the features offered by `@emotion/babel-plugin`. On the other hand, there's no reason not to use `@emotion/babel-plugin` if you are already using Babel to transpile your TypeScript code.

### With the old JSX transform

If you are unable to upgrade to the `react-jsx` transform, you will need to specify the JSX factory at the top of every file:

```tsx
/** @jsx jsx */
import { jsx } from '@emotion/react'

<div css={{ background: 'black' }} />
```

As a result you may be not able to use react fragment shorthand syntax - `<></>`, but still you can use `<Fragment></Fragment>`.
This is a limitation of the TypeScript compiler not being able to independently specify jsx pragma and jsxFrag pragma.
As a result, you may be not able to use the shorthand syntax `<></>` for React fragments, but you can still use `<Fragment></Fragment>`. This is a limitation of the TypeScript compiler not being able to independently specify jsx pragma and jsxFrag pragma.

You can still use the css helper and pass the className yourself (ensure you are importing from the `@emotion/css` package, not `@emotion/react`).

```tsx
import { css } from '@emotion/css'

<div className={css({ background: 'black' })} />
const el = <div className={css({ background: 'black' })} />
```

### `css` prop

When using our JSX factories the support for `css` prop is being added only for components that accepts `className` prop as they take provided `css` prop, resolves it and pass the generated `className` to the rendered component.

If using the automatic runtime you should just add this to your `tsconfig.json` to let TypeScript know where it should look for the `JSX` namespace:
```json
{
"compilerOptions": {
"jsxImportSource": "@emotion/react"
}
}
```

The same `JSX` namespace is resolved if you are still using the classic runtime through the `@jsx` pragma. However, it's not possible to leverage `css` prop support being added conditionally based on a type of rendered component when one is not using our jsx pragma or the automatic runtime. For those cases when people use our pragma implicitly (for example when using our `@emotion/babel-preset-css-prop`) we have a special file that can be imported once to add support for the `css` prop globally, for all components. Use it like this:
It's not possible to leverage `css` prop support being added conditionally based on the type of a rendered component when not using our jsx pragma or the `react-jsx` transform. If you use our pragma implicitly (for example when using our `@emotion/babel-preset-css-prop`) we have a special file that can be imported once to add support for the `css` prop globally, for all components. Use it like this:

```ts
/// <reference types="@emotion/react/types/css-prop" />
```

## @emotion/styled

`@emotion/styled` works with TypeScript without any additional configuration.

### HTML/SVG elements

```tsx
Expand Down Expand Up @@ -170,13 +173,12 @@ interface ComponentProps {
label: string
}

const Component: FC<ComponentProps> = ({
label,
className
}) => <div className={className}>{label}</div>
const Component: FC<ComponentProps> = ({ label, className }) => (
<div className={className}>{label}</div>
)

const StyledComponent0 = styled(Component)`
color: ${props => props.label === 'Important' ? 'red' : 'green'};
color: ${props => (props.label === 'Important' ? 'red' : 'green')};
`

const StyledComponent1 = styled(Component)({
Expand All @@ -195,12 +197,12 @@ const App = () => (

Sometimes you want to wrap an existing component and override the type of a prop. Emotion allows you to specify a `shouldForwardProp` hook to filter properties which should be passed to the wrapped component.

If you make `shouldForwardProp` a [type guard](https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards) then only the props from the type guard will be exposed.
If you make `shouldForwardProp` a [type guard](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) then only the props from the type guard will be exposed.

For example:

``` ts
const Original: React.FC<{ prop1: string, prop2: string }> = () => null
```ts
const Original: React.FC<{ prop1: string; prop2: string }> = () => null

interface StyledOriginalExtraProps {
// This prop would conflict with the `prop2` on Original
Expand Down Expand Up @@ -286,7 +288,7 @@ declare module '@emotion/react' {

// You are also able to use a 3rd party theme this way:
import '@emotion/react'
import { LibTheme } from 'some-lib'
import { LibTheme } from 'some-lib'

declare module '@emotion/react' {
export interface Theme extends LibTheme {}
Expand All @@ -307,38 +309,14 @@ const Button = styled('button')`
export default Button
```

If you were previously relying on `theme` being an `any` type, you have to restore compatibility with:
If you were previously relying on `theme` being an `any` type, you can restore compatibility with:

_emotion.d.ts_

```ts
import '@emotion/react'

declare module '@emotion/react' {
export interface Theme extends Record<string, any> {}
export interface Theme extends Record<string, any> {}
}
```

### TypeScript < 2.9

For Typescript <2.9, the generic type version only works with object styles due to https://github.com/Microsoft/TypeScript/issues/11947.

You can work around this by specifying the prop types in your style callback:

``` ts
const StyledComponent0 = styled(Component)`
color: red;
background: ${(props: StyledComponentProps) =>
props.bgColor};
`
```

NOTE: This approach you will have to perform the intersection with the component props yourself to get at the component props

``` ts
const StyledComponent0 = styled(Component)`
color: red;
background: ${(props: StyledComponentProps & ComponentProps) =>
props.bgColor};
`
```

0 comments on commit 2790dc9

Please sign in to comment.