TypeScript and ES6 Syntax Essentials
TypeScript's syntax documentation is thorough; what actually takes time is configuration and type boundaries: turn strict on and the screen fills with errors, third-party libraries' types don't line up, and any quietly spreads out from some callback.
These notes are organized in four sections — "compiler options → type system → ES6 syntax → common pitfalls" — and every example is meant to be usable directly in a project.
What TypeScript Gives You, and What It Costs
TypeScript adds a compile-time type system on top of JavaScript:
- Benefits: the editor can autocomplete and jump to definitions, refactoring can locate every reference, and some runtime errors are moved up to compile time
- Costs: an extra compile/build step; when third-party libraries lack types you have to write
d.tsyourself; over-engineering types slows development down
The key fact: types are completely erased after compilation. The output is plain JavaScript, with no type checking at runtime. So don't count on the type system to block invalid data — JSON returned by an API still needs validation.
1. tsconfig Options Worth Enabling First
| Option | Suggested value | Reason |
|---|---|---|
strict | true | Turns on the group of checks below at once; the default prerequisite for new projects |
noImplicitAny | pulled in by strict | Bans implicit any, preventing silent type degradation |
strictNullChecks | pulled in by strict | null/undefined can no longer be assigned to arbitrary types |
noUncheckedIndexedAccess | true | Array index access returns T | undefined, forcing you to handle out-of-bounds |
target | ES2022 or higher | Determines how far syntax is downleveled |
moduleResolution | bundler (frontend) | Matches Vite/webpack resolution rules |
skipLibCheck | true | Skips type checking of node_modules, noticeably speeding up builds |
The most common error after turning on strict is "object is possibly null" — that's not noise, it's telling you to handle the boundary explicitly.
2. Common Type System Patterns
2.1 Interfaces and Type Aliases
interface Person {
firstName: string
lastName: string
}
type Point = { x: number; y: number }The two are interchangeable in most situations. The difference: interface supports declaration merging (same name automatically combines), making it suitable for describing extensible object structures; type can express unions, conditional types, and other forms interface can't.
2.2 Unions and Intersections
type Status = 'idle' | 'loading' | 'success' | 'error' // 字面量联合,比 enum 更轻
type WithId = { id: string }
type User = WithId & { name: string } // 交叉类型 = 同时满足Literal unions are better suited to the frontend than enum: smaller output, and you can compare strings directly.
2.3 Generics and Constraints
function first<T>(list: T[]): T | undefined {
return list[0]
}
function pick<T extends object, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key]
}Here extends means a constraint (the minimum shape T must satisfy), not inheritance.
2.4 Type Narrowing
TypeScript automatically narrows types based on control flow:
function format(v: string | number | Date): string {
if (typeof v === 'string') return v // string
if (typeof v === 'number') return String(v) // number
return v.toISOString() // Date
}For a custom type guard, the return type must be written as v is Person for the compiler to accept it:
function isPerson(v: unknown): v is Person {
return typeof v === 'object' && v !== null && 'firstName' in v
}2.5 unknown and any
any: gives up checking, and it infects every downstream variableunknown: means "don't know yet"; it must be narrowed before use
External input (JSON.parse, event callbacks, fetch return values) should be declared as unknown and then validated. This is how you put the type system where it actually matters.
3. ES6+ Syntax Essentials
3.1 let / const and the Temporal Dead Zone
let x = 10
const y = 20
x = 15 // 允许
// y = 25 // TypeError: Assignment to constant variableconst only guarantees the binding doesn't change; the object's internals can still be modified. Also, accessing a let/const variable before its declaration throws a ReferenceError (the temporal dead zone), unlike var, which gives you undefined.
3.2 Arrow Functions and this
const add = (a, b) => a + bThe key difference: arrow functions have no this of their own; they capture the outer this at definition time. So:
- Want the outer
thisinside a callback → use an arrow function - Need dynamic
this(object methods, methods in Vue's Options API) → usefunction
Arrow functions also can't be called with new and have no arguments.
3.3 Template Strings and Destructuring
const name = 'John'
console.log(`Hello, ${name}!`)
let [a, b] = [1, 2]
let { name: userName, age = 18 } = { name: 'John' } // 可重命名、可设默认值Destructuring is often used for function parameters; combined with default values it eliminates a pile of null checks:
function connect({ host = '127.0.0.1', port = 6379 } = {}) { /* ... */ }3.4 Spread and Rest
let arr2 = [1, ...[2, 3], 4] // [1, 2, 3, 4]
let { id, ...rest } = { id: 1, a: 2, b: 3 } // rest = { a: 2, b: 3 }Note: object spread is a shallow copy; nested objects are still the same reference.
3.5 class and Inheritance
class Animal {
constructor(name) {
this.name = name
}
move(meters) {
console.log(`${this.name} moved ${meters}m.`)
}
}
class Dog extends Animal {
bark() {
console.log('Woof!')
}
}class is syntactic sugar over prototype inheritance, but behavior differs: class bodies are in strict mode by default, methods are non-enumerable, and new is required to call them.
3.6 Promise and async/await
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
async function run() {
await sleep(1000)
console.log('done')
}An async function always returns a Promise; await only pauses the current function and doesn't block the thread. For concurrent work use Promise.all — don't write serial awaits, which is the most common performance problem.
3.7 Modules
// math.js
export function add(x, y) {
return x + y
}
// main.js
import { add } from './math.js'ESM is statically parsed, so import must be at the top level, which is what lets bundlers do tree-shaking. When mixing with CommonJS, note that __dirname and require don't exist in ESM.
4. Common Pitfalls
anycontagion: once ananyvariable takes part in an operation, the result is alsoany, and type checking fails all the way down. Preferunknownplus validation.- Overusing
asassertions:asperforms no runtime check; a wrong assertion still compiles and only blows up at runtime. Rely on narrowing rather than assertions. enumoutput: a plainenumgenerates a runtime object (extra size + unexpected behavior); in the vast majority of cases, use a literal union instead.- Optional properties vs
undefined:{ a?: string }and{ a: string | undefined }have different semantics underexactOptionalPropertyTypes; the former means "this key may be absent." for...inon arrays: it iterates keys on the prototype chain; for arrays always usefor...oforforEach.
Related Reading
- Getting Started with Full-Stack Next.js Apps: how these syntax features are actually used in a framework
- Getting Started with Caddy: Automatic HTTPS and Reverse Proxy: hosting and caching static output
