Appearance
TypeScript how-to
Strict TypeScript for a Next brochure app. Production builds fail on type errors.
Install
bash
pnpm add -D typescript @types/node @types/react @types/react-dom| Item | Detail |
|---|---|
| Project | tsconfig.json |
| Strict | strict, noUncheckedIndexedAccess |
| Alias | @/* → repo root |
| Nested packages | Own tsconfig (e.g. CMS Studio) — excluded from root tsc |
Commands
bash
pnpm run typecheck # tsc --noEmit
pnpm run build # Next build also typechecks
pnpm run check # includes typecheckImplementation examples
Strict tsconfig highlights
json
{
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true,
"jsx": "react-jsx",
"moduleResolution": "bundler",
"paths": { "@/*": ["./*"] },
"noEmit": true
},
"exclude": ["node_modules", "studio"]
}unknown + narrowing
ts
function parseBody(body: unknown): string {
if (!body || typeof body !== 'object' || !('email' in body)) {
throw new Error('missing email');
}
const email = (body as { email: unknown }).email;
if (typeof email !== 'string') throw new Error('email must be string');
return email;
}Indexed access
ts
const first = items[0]; // T | undefined
if (first === undefined) return;Path alias
ts
import { loadSiteConfig } from '@/lib/siteConfigContent';