# Install TypeScript as a dev dependency
npm install typescript --save-dev
# Compile a specific TypeScript file (e.g., app.ts)
npx tsc app.ts
tsc
(TypeScript Compiler)自行把 .ts/.tsx
解析成 TS AST,然后做类型检查、产生 .js
或 .d.ts
等输出。tsserver
则在编辑器里作为长驻进程,基于 tsc
API 提供 IntelliSense、跳转、重构等语言服务。它用的是同一份 TypeScript Compiler API 的 AST,所以 tsc
和 tsserver
“共享”这一套解析/类型引擎。Create a tsconfig.json
in your project root. This configuration enables strict type-checking and modern JavaScript features.
{
"compilerOptions": {
"target": "ES2020", // Use modern JS features
"module": "ESNext", // Use the latest module system
"moduleResolution": "node", // Node module resolution
"outDir": "./dist", // Compiled output directory
"rootDir": "./", // Root of your source files
"strict": true, // Enable all strict type-checking options
"esModuleInterop": true, // Allow default imports from non-ES modules
"skipLibCheck": true, // Skip type checking of declaration files
"forceConsistentCasingInFileNames": true, // Enforce consistent file naming
"resolveJsonModule": true, // Import JSON files as modules
"allowSyntheticDefaultImports": true, // Allow default imports even if module doesn't have one
"strictNullChecks": true, // Null and undefined are separate types
"noImplicitAny": true, // Disallow variables with an implied any type
"noUnusedLocals": true, // Error on unused locals
"noUnusedParameters": true, // Error on unused function parameters
"noFallthroughCasesInSwitch": true // Prevent fall-through in switch cases
},
"include": ["src/**/*.ts"],
"exclude": ["node_modules", "dist"]
}
Primitive Types: boolean
, bigint
, null
, number
, string
, symbol
, undefined
Extended Types: any
, unknown
, never
, void
// Primitive Types
let num: number = 42;
let isDone: boolean = false;
let username: string = "Merrick";
// Array and Tuple
let numbers: number[] = [1, 2, 3];
let tuple: [number, string] = [1, "hello"];
// Object Type
let user: { name: string; age: number } = { name: "Merrick", age: 22 };
// Extended Type - Use sparingly
let anything: any = "This can be any type";
<aside> 💡
Avoid any
unless absolutely necessary; prefer unknown
when possible.
</aside>
Explicit return types make functions easier to read and maintain:
// Function Declaration with explicit return type
function add(a: number, b: number): number {
return a + b;
}
// Arrow Function with type inference
const multiply = (x: number, y: number): number => x * y;
// Usage examples
console.log(add(5, 3)); // 8
console.log(multiply(5, 3)); // 15