Capítulo 428 de 456

TypeScript

Core Idea

Full guide to Next.js's built-in TypeScript-first experience: auto-setup, next-env.d.ts, statically typed links, typed env vars, and how to configure/disable type checking.

Key Concepts

  • Auto-setup: renaming a file to .ts/.tsx and running next dev/next build auto-installs deps and creates tsconfig.json.
  • TypeScript 7: doesn't ship a JS compiler API yet; Next.js uses the project-local tsc CLI by default (experimental.useTypeScriptCli) so no extra config is needed once TS7 is installed.
  • next-env.d.ts: auto-generated, references Next.js types; add to .gitignore; never edit manually; regenerated by next dev, next build, or next typegen.
  • typedRoutes: opt-in static typing for href in next/link (and next/navigation methods push/replace/prefetch in App Router). Literal strings validated automatically; non-literal strings need as Route cast.
  • experimental.typedEnv: generates IntelliSense types for loaded env vars in .next/types during dev.
  • typescript.tsconfigPath: use a different tsconfig for builds vs. editor (e.g. relaxed checks in CI/monorepo).
  • typescript.ignoreBuildErrors: dangerously skip type checking entirely in production builds.
  • Node.js native TS resolver for next.config.ts: on Node v22.10.0+ with process.features.typescript, next.config.ts/.mts can use native ESM (top-level await, dynamic import()).

Code Examples

const nextConfig: NextConfig = {
  typedRoutes: true,
}
  • O que demonstra: ativa links tipados estaticamente (requer TypeScript no projeto).
'use client'
import type { Route } from 'next'
import Link from 'next/link'
import { useRouter } from 'next/navigation'

export default function Example() {
  const router = useRouter()
  const slug = 'nextjs'
  return (
    <>
      <Link href="/about" />
      <Link href={`/blog/${slug}`} />
      <Link href={('/blog/' + slug) as Route} />
      <button onClick={() => router.push('/about')}>Push About</button>
      <button onClick={() => router.push(('/blog/' + slug) as Route)}>Push Non-literal</button>
    </>
  )
}
  • O que demonstra: strings literais são validadas automaticamente; strings dinâmicas exigem cast as Route.
function Card<T extends string>({ href }: { href: Route<T> | URL }) {
  return <Link href={href}><div>My Card</div></Link>
}
  • O que demonstra: como aceitar href tipado em componente wrapper genérico de Link.

Reference Tables

VersionChanges
v15.0.0next.config.ts support added for TypeScript projects.
v13.2.0Statically typed links available in beta.
v12.0.0SWC used by default to compile TypeScript/TSX.
v10.2.1Incremental type checking support added.

Anti-patterns

  • Editar next-env.d.ts manualmente: é sobrescrito automaticamente; crie um arquivo separado (ex. new-types.d.ts) e referencie no tsconfig.json.
  • Setar ignoreBuildErrors: true sem type-check em outro passo do pipeline: build "perigoso" que ignora erros reais de tipo.
  • Não adicionar .next/types/**/*.ts ao include do tsconfig quando o projeto não foi criado via create-next-app: quebra os tipos de rotas gerados.

Key Takeaways

  1. typedRoutes funciona em App e Pages Router para next/link, mas só tipa next/navigation (não next/router) no App Router.
  2. next typegen gera tipos de rota sem build completo, útil pra CI (next typegen && tsc --noEmit).
  3. Em dev, só tsconfig.json é observado; ao usar typescript.tsconfigPath com outro arquivo, reinicie o dev server pra aplicar mudanças.
  4. experimental.typedEnv exclui .env.production* por padrão; rode next dev com NODE_ENV=production pra incluir essas vars.

Connects To

  • typescript (ch422): config de ignoreBuildErrors/tsconfigPath referenciada aqui em detalhe.
  • useTypeScriptCli (ch425): mecanismo por trás do type-checking padrão com TS7.
  • next typegen CLI (ch432): comando que gera os tipos de rota usados por typedRoutes.