JavaScript / TypeScript 语法速记表
变量声明
1 2 3 4 5 6
| var x = 10;
let y = 20; const z = 30;
|
数据类型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| let str: string = "Hello"; let num: number = 42; let bool: boolean = true; let undef: undefined = undefined; let nul: null = null; let sym: symbol = Symbol("id");
let obj: object = { key: "value" }; let arr: number[] = [1, 2, 3]; let func: Function = () => {};
let anyType: any = "anything"; let tuple: [string, number] = ["a", 1]; enum Color { Red, Green, Blue, } let unknownType: unknown; let neverType: never; let voidType: void;
|
运算符
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| + - * / % ** ++ --
== === != !== > < >= <=
&& || !
= += -= *= /= %=
?? ?. ...
|
函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| function add(a: number, b: number): number { return a + b; }
const multiply = function (a, b) { return a * b; };
const divide = (a, b) => a / b; const sayHi = () => console.log("Hi");
function greet(name = "Guest") {}
function sum(...numbers) {}
type AddFunc = (a: number, b: number) => number;
|
类与面向对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| class Animal { name: string; private age: number; protected species: string; static count: number = 0;
constructor(name: string) { this.name = name; }
speak(): void { console.log("Sound"); }
get getAge(): number { return this.age; } set setAge(value: number) { this.age = value; } }
class Dog extends Animal { bark(): void { console.log("Woof!"); }
override speak(): void { console.log("Woof!"); } }
abstract class Shape { abstract area(): number; }
interface Person { name: string; age: number; greet(): void; }
class Student implements Person { name: string; age: number; greet() { console.log("Hello"); } }
|
数组操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| arr.push(), arr.pop(), arr.shift(), arr.unshift(); arr.map(), arr.filter(), arr.reduce(), arr.forEach(); arr.find(), arr.findIndex(), arr.some(), arr.every(); arr.slice(), arr.splice(), arr.concat(), arr.join(); arr.sort(), arr.reverse();
const [first, ...rest] = [1, 2, 3]; const { name, age } = person;
const newArr = [...oldArr, 4]; const newObj = { ...oldObj, key: "value" };
|
对象操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| const name = "John"; const person = { name, age: 30 }; const obj = { ["key" + 1]: "value" };
const obj = { method() { return this; }, };
Object.keys(obj), Object.values(obj), Object.entries(obj); Object.assign(target, source); Object.freeze(obj); Object.seal(obj);
|
异步编程
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| const promise = new Promise((resolve, reject) => { setTimeout(() => resolve("Done"), 1000); });
promise .then((result) => console.log(result)) .catch((error) => console.error(error)) .finally(() => console.log("Complete"));
async function fetchData() { try { const data = await fetch(url); const result = await data.json(); return result; } catch (error) { console.error(error); } }
Promise.all([p1, p2]); Promise.race([p1, p2]); Promise.allSettled([p1, p2]); Promise.any([p1, p2]);
|
模块系统
1 2 3 4 5 6 7 8 9 10 11
| export const PI = 3.14; export function add() {} export default class MyClass {} export { var1, var2 as alias };
import MyClass from "./module"; import { var1, var2 as alias } from "./module"; import * as Module from "./module"; import("./module").then((module) => {});
|
字符串
1 2 3 4 5 6 7 8 9
| const greeting = `Hello ${name}, you are ${age} years old`;
str.includes(), str.startsWith(), str.endsWith(); str.repeat(), str.padStart(), str.padEnd(); str.trim(), str.trimStart(), str.trimEnd(); str.replace(), str.replaceAll(); str.slice(), str.substring(), str.substr();
|
类型操作 (TypeScript)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| let x: number = 5;
type ID = string | number; type User = { id: ID; name: string };
let value: string | number;
type Combined = TypeA & TypeB;
let str = value as string; let len = (<string>value).length;
function identity<T>(arg: T): T { return arg; } interface Generic<T> { value: T; }
type IsString<T> = T extends string ? true : false;
type Readonly<T> = { readonly [K in keyof T]: T[K] }; type Partial<T> = { [K in keyof T]?: T[K] };
|
错误处理
1 2 3 4 5 6 7 8 9
| try { throw new Error("Something went wrong"); } catch (error) { console.error(error); } finally { }
|
ES6+ 新特性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| const { a, b } = obj; const [x, y] = arr;
function f(x = 1, y = 2) {}
function f(...args) {}
const value = obj?.prop?.nested;
const result = input ?? "default";
const big = 9007199254740991n;
import("./module.js").then((module) => {});
|
常用数组/对象方法链
1 2 3 4 5 6
| array .filter((item) => item.active) .map((item) => ({ ...item, processed: true })) .sort((a, b) => a.id - b.id) .reduce((acc, curr) => acc + curr.value, 0);
|
实用代码片段
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| const deepCopy = JSON.parse(JSON.stringify(obj));
const deepCopy = structuredClone(obj);
const unique = [...new Set(array)];
const merged = Object.assign({}, obj1, obj2);
const merged = { ...obj1, ...obj2 };
const isEmpty = Object.keys(obj).length === 0;
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const debounce = (func, wait) => { let timeout; return (...args) => { clearTimeout(timeout); timeout = setTimeout(() => func(...args), wait); }; };
|
constructor 关键字
constructor 是类(class)中用于定义构造函数的关键字。构造函数是一种特殊的方法,在使用 new 创建类实例时自动调用,用于初始化对象的属性和状态。
new 关键字
new 是用于创建对象实例的操作符关键字。它与构造函数结合使用,执行类的实例化过程。
- 作用:
- 创建一个新对象。
- 将构造函数的 this 绑定到新对象。
- 执行构造函数代码。
- 如果构造函数未显式返回对象,则返回新创建的对象。
- 执行步骤(内部机制):
- 创建一个空对象 {}。
- 将该对象的原型(proto)设置为构造函数的 prototype。
- 将 this 绑定到新对象并调用构造函数。
- 返回该对象(除非构造函数返回其他对象)。
- 语法示例:
1 2
| const person = new Person('Alice', 30); person.greet();
|
- 常见错误:
- 直接调用构造函数而不使用 new(如 Person(‘Alice’, 30)),会导致 this 指向全局对象(严格模式下为 undefined),可能造成意外行为。
两者关系
- new 操作符触发类的 constructor 方法执行。
- 它们共同实现了 JavaScript 的类实例化机制,支持原型继承和面向对象编程范式。
在 TypeScript 中,这些关键字的行为与 JavaScript 完全一致,但 TypeScript 通过类型注解提供了更强的静态类型检查,提升了代码的安全性和可维护性。
DST:
- const > let > var 优先使用 const
- === 代替 == 严格相等判断
- 箭头函数保持 this 绑定
- 模板字符串代替拼接
- 解构简化代码
- Promise 处理异步,async/await 更可读
- 可选链和空值合并处理 null/undefined