Skip to content

Commit

Permalink
feat: Add a TypeScript usage section to the README (#827)
Browse files Browse the repository at this point in the history
* Add a TypeScript usage section to the README

Additional examples should be added, such as how to type a page that requires additional props beside the t function.

* feat: Add TS doc with explanation on prop-types

Remove `prop-types` from TS example.

* feat: Move TS doc to separate file

* feat: Restore README formatting
  • Loading branch information
allan2 authored Sep 15, 2020
1 parent 9a4ca30 commit b3fb7a2
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,10 @@ _This table contains options which are specific to next-i18next. All other [i18n
- [Localising `next/head` requires special consideration due to NextJs internals](https://github.com/isaachinman/next-i18next/issues/251#issuecomment-479421852).
- [How to use multiple namespaces in the same component](https://github.com/isaachinman/next-i18next/issues/762#issuecomment-661348457)

## Usage with TypeScript

`next-i18next` is written in TypeScript and has full support for it. Refer to the usage guide [here](./TYPESCRIPT.md).

## Contributors

Thanks goes to these wonderful people ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)):
Expand Down
41 changes: 41 additions & 0 deletions TYPESCRIPT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Usage with TypeScript

`next-i18next` has full support for TypeScript. Types are included with the `next-i18next` package.

## Usage with components

To type the [t function](https://www.i18next.com/overview/api), use the `TFunction` type provided by `next-i18next`:

```tsx
// this is the same TFunction from 'i18next'
import { TFunction } from 'next-i18next';

const Heading = ({ t }: { readonly t: TFunction }) => <h1>{t('heading')}</h1>;
```

## Usage with pages

Typing a [page](https://nextjs.org/docs/basic-features/pages) with the t function as the singular prop is similar to JS, but with TS instead of `prop-types`.
TypeScript validates at _compile time_ while [`prop-types`](https://github.com/facebook/prop-types) validates at _runtime_.
Although `prop-types` can do things that TS can't like value validation, TS alone will suffice in most cases.

```tsx
import { TFunction } from 'next-i18next';
import { withTranslation } from '../i18n';

const Page = ({ t }: { readonly t: TFunction }) => (
<div>
<h1>{t('heading')}</h1>
</div>
);

Page.getInitialProps = async () => ({
namespacesRequired: ['common'],
});

export default withTranslation('common')(Page);
```

## More

The complete list of exported types can be found [here](./types.d.ts).

0 comments on commit b3fb7a2

Please sign in to comment.