-
-
Notifications
You must be signed in to change notification settings - Fork 763
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Add a TypeScript usage section to the README (#827)
* 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
Showing
2 changed files
with
45 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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). |