https://github.com/emanuelefavero/nextjs-typescript
A cheat sheet repository for Typescript in NextJS
https://github.com/emanuelefavero/nextjs-typescript
cheatsheet next nextjs typescript
Last synced: 6 months ago
JSON representation
A cheat sheet repository for Typescript in NextJS
- Host: GitHub
- URL: https://github.com/emanuelefavero/nextjs-typescript
- Owner: emanuelefavero
- Created: 2023-01-23T20:06:01.000Z (over 2 years ago)
- Default Branch: main
- Last Pushed: 2023-01-30T22:55:15.000Z (over 2 years ago)
- Last Synced: 2025-02-04T16:50:29.460Z (8 months ago)
- Topics: cheatsheet, next, nextjs, typescript
- Homepage:
- Size: 1000 Bytes
- Stars: 1
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Typescript in NextJS
> Learn more about [Typescript in NextJS](https://nextjs.org/docs/basic-features/typescript)
This is a cheat sheet repository for Typescript in NextJS
## Example Projects
- [NextJS Blog TypeScript](https://github.com/emanuelefavero/nextjs-blog-typescript)
## Create a new NextJS App with TypeScript
- `npx create-next-app APP-NAME --typescript`
#### Create a new NextJS App with TypeScript and ESLint
- `npx create-next-app APP-NAME --typescript --eslint`
## Add Typescript to an existing NextJS App
Create a `tsconfig.json` file in the root of the project (`touch tsconfig.json`)
> NextJS will automatically detect and configure this file for you after you run `npm run dev` or `npm run build`
Alternatively, you can:
- `npm install --save-dev typescript @types/react @types/node`
## **The @ alias**
- Remember to add the @ alias for the root folder in `jsconfig.json` or `tsconfig.json`:
```json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
// Use @ as an alias for the root directory
"@/*": ["./*"]
}
}
}
```> Remember also to rename your files from `.js` to `.ts` and `.tsx`
## Typescript strict mode
- Strict mode is turned off by default in NextJS, when you feel comfortable with Typescript you can turn it on by adding the following to your `tsconfig.json` file:
```json
{
"compilerOptions": {
"strict": true
}
}
```## **NextJS Typescript types**
- Static Site Generation (SSG) and Server-side Rendering (SSR)
```ts
import { GetStaticProps, GetStaticPaths, GetServerSideProps } from 'next'export const getStaticProps: GetStaticProps = async (context) => {
// ...
}export const getStaticPaths: GetStaticPaths = async () => {
// ...
}export const getServerSideProps: GetServerSideProps = async (context) => {
// ...
}
```- API Routes
```ts
import type { NextApiRequest, NextApiResponse } from 'next'export default function handler(req: NextApiRequest, res: NextApiResponse) {
res.status(200).json({ name: 'John Doe' })
}
```- Custom App
```ts
import type { AppProps } from 'next/app'export default function MyApp({ Component, pageProps }: AppProps) {
return
}
```
---
[**Go To Top ⬆️**](#demo)