TypeScript

Next.js, React uygulamanızı oluşturmak için TypeScript öncelikli bir geliştirme deneyimi sunar.

Gerekli paketleri otomatik olarak yüklemek ve uygun ayarları yapılandırmak için yerleşik TypeScript desteği ile birlikte gelir.

New Projects

create-next-app artık varsayılan olarak TypeScript ile birlikte geliyor.

Terminal
npx create-next-app@latest

Existing Projects

Bir dosyayı .ts / .tsx olarak yeniden adlandırarak projenize TypeScript ekleyin. Gerekli bağımlılıkları otomatik olarak yüklemek için next dev ve next build adreslerini çalıştırın ve önerilen yapılandırma seçeneklerini içeren bir tsconfig.json dosyası ekleyin.

Zaten bir jsconfig.json dosyanız varsa, paths derleyici seçeneğini eski jsconfig.json dosyasından yeni tsconfig.json dosyasına kopyalayın ve eski jsconfig.json dosyasını silin.

Minimum TypeScript Version

İçe aktarma adlarında tür değiştiriciler ve performans iyileştirmeleri gibi sözdizimi özelliklerini elde etmek için TypeScript 'in en az v4.5.2 sürümünde olmanız şiddetle tavsiye edilir.

Static Generation and Server-side Rendering

İçin getStaticProps, getStaticPathsve getServerSidePropssırasıyla GetStaticProps, GetStaticPaths ve GetServerSideProps türlerini kullanabilirsiniz:

pages/blog/[slug].tsx
import { GetStaticProps, GetStaticPaths, GetServerSideProps } from 'next'
 
export const getStaticProps = (async (context) => {
  // ...
}) satisfies GetStaticProps
 
export const getStaticPaths = (async () => {
  // ...
}) satisfies GetStaticPaths
 
export const getServerSideProps = (async (context) => {
  // ...
}) satisfies GetServerSideProps

Bilmekte fayda var: satisfies, 4.9 sürümünde TypeScript'e eklenmiştir. TypeScript'in en son sürümüne yükseltmenizi öneririz.

API Routes

Aşağıda, API rotaları için yerleşik türlerin nasıl kullanılacağına dair bir örnek verilmiştir:

import type { NextApiRequest, NextApiResponse } from 'next'
 
export default function handler(req: NextApiRequest, res: NextApiResponse) {
  res.status(200).json({ name: 'John Doe' })
}

Yanıt verilerini de yazabilirsiniz:

import type { NextApiRequest, NextApiResponse } from 'next'
 
type Data = {
  name: string
}
 
export default function handler(
  req: NextApiRequest,
  res: NextApiResponse<Data>
) {
  res.status(200).json({ name: 'John Doe' })
}

Custom App

Özel bir App adresiniz varsa, yerleşik AppProps türünü kullanabilir ve dosya adını aşağıdaki gibi ./pages/_app.tsx olarak değiştirebilirsiniz:

import type { AppProps } from 'next/app'
 
export default function MyApp({ Component, pageProps }: AppProps) {
  return <Component {...pageProps} />
}

Path aliases and baseUrl

Next.js otomatik olarak tsconfig.json "paths" ve "baseUrl" seçeneklerini destekler.

Bu özellik hakkında daha fazla bilgiyi Modül Yolu takma adları belgesinde bulabilirsiniz.

Type checking next.config.js

next.config.js dosyası Babel veya TypeScript tarafından ayrıştırılmadığı için bir JavaScript dosyası olmalıdır, ancak aşağıdaki gibi JSDoc kullanarak IDE'nize bazı tür denetimleri ekleyebilirsiniz:

// @ts-check
 
/**
 * @type {import('next').NextConfig}
 **/
const nextConfig = {
  /* config options here */
}
 
module.exports = nextConfig

Incremental type checking

v10.2.1 Next.js, tsconfig.json adresinizde etkinleştirildiğinde artımlı tür denetim ini desteklediğinden, bu daha büyük uygulamalarda tür denetimini hızlandırmaya yardımcı olabilir.

Ignoring TypeScript Errors

Next.js, projenizde TypeScript hataları mevcut olduğunda üretim derlemenizde başarısız olur (next build).

Next.js'nin uygulamanızda hatalar olsa bile tehlikeli bir şekilde üretim kodu üretmesini istiyorsanız, yerleşik tür denetimi adımını devre dışı bırakabilirsiniz.

Devre dışı bırakılmışsa, derleme veya dağıtım işleminizin bir parçası olarak tür denetimlerini çalıştırdığınızdan emin olun, aksi takdirde bu çok tehlikeli olabilir.

next.config.js adresini açın ve typescript yapılandırmasında ignoreBuildErrors seçeneğini etkinleştirin:

next.config.js
module.exports = {
  typescript: {
    // !! WARN !!
    // Dangerously allow production builds to successfully complete even if
    // your project has type errors.
    // !! WARN !!
    ignoreBuildErrors: true,
  },
}

Custom Type Declarations

Özel türleri bildirmeniz gerektiğinde, next-env.d.ts adresini değiştirmek isteyebilirsiniz. Ancak bu dosya otomatik olarak oluşturulduğundan yaptığınız tüm değişiklikler üzerine yazılacaktır. Bunun yerine, yeni bir dosya oluşturmalısınız, buna new-types.d.ts diyelim ve tsconfig.json adresinizde bu dosyaya referans verin:

tsconfig.json
{
  "compilerOptions": {
    "skipLibCheck": true
    //...truncated...
  },
  "include": [
    "new-types.d.ts",
    "next-env.d.ts",
    ".next/types/**/*.ts",
    "**/*.ts",
    "**/*.tsx"
  ],
  "exclude": ["node_modules"]
}

Version Changes

Version Changes
v13.2.0 Statically typed links are available in beta.
v12.0.0 SWC is now used by default to compile TypeScript and TSX for faster builds.
v10.2.1 Incremental type checking support added when enabled in your tsconfig.json.