Skip to content

Latest commit

 

History

History
80 lines (62 loc) · 1.72 KB

typescript.md

File metadata and controls

80 lines (62 loc) · 1.72 KB

Use Twin with TypeScript + emotion

First up, you’ll need to install some types for React:

npm install -D @types/react
# or
yarn add @types/react -D

Twin then needs some type declarations added, otherwise you’ll see errors like this:

Module '"../node_modules/twin.macro/types"' has no exported member 'styled'.
# or
Module '"../node_modules/twin.macro/types"' has no exported member 'css'.
# or
Property 'css' does not exist on type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'.

To fix this, create a twin.d.ts file in your project root (src/twin.d.ts with create-react-app) and add these declarations:

// twin.d.ts
import 'twin.macro'
import styledImport from '@emotion/styled'
import { css as cssImport } from '@emotion/react'

// The css prop
// https://emotion.sh/docs/typescript#css-prop
import {} from '@emotion/react/types/css-prop'

declare module 'twin.macro' {
  // The styled and css imports
  const styled: typeof styledImport
  const css: typeof cssImport
}

// The 'as' prop on styled components
declare global {
  namespace JSX {
    interface IntrinsicAttributes<T> extends DOMAttributes<T> {
      as?: string
    }
  }
}

Then add the following in tsconfig.json:

// tsconfig.json
{
  "files": ["twin.d.ts"],
  // or
  // "include": ["twin.d.ts"],
}

Now that you’ve added the definitions, you can use these imports:

import tw, { css, styled, theme } from 'twin.macro'

And these props:

<div tw="">
<div css={}>

Installation guides