2026 年几乎必选的 JavaScript 超集
// 基本类型
let name: string = 'John';
let age: number = 30;
let isActive: boolean = true;
let nullable: string | null = null;
let optional: string | undefined = undefined;
// 数组
let numbers: number[] = [1, 2, 3];
let strings: Array<string> = ['a', 'b', 'c'];
// 元组
let person: [string, number] = ['John', 30];
// 枚举
enum Direction {
Up = 1,
Down,
Left,
Right
}
let dir: Direction = Direction.Up;
// any 类型
let anything: any = 'hello';
anything = 123;
// void 类型
function log(): void {
console.log('Hello');
}
// never 类型
function throwError(): never {
throw new Error('Error');
}// 接口定义
interface Person {
name: string;
age: number;
email?: string; // 可选属性
readonly id: number; // 只读属性
}
// 使用接口
const person: Person = {
id: 1,
name: 'John',
age: 30
// email 是可选的
};
// 函数接口
interface AddFunction {
(a: number, b: number): number;
}
const add: AddFunction = (a, b) => a + b;
// 类实现接口
class Employee implements Person {
id: number;
name: string;
age: number;
constructor(id: number, name: string, age: number) {
this.id = id;
this.name = name;
this.age = age;
}
}// 泛型函数
function identity<T>(value: T): T {
return value;
}
const str = identity('hello'); // 类型为 string
const num = identity(123); // 类型为 number
// 泛型接口
interface Container<T> {
value: T;
get(): T;
}
// 泛型类
class Box<T> implements Container<T> {
value: T;
constructor(value: T) {
this.value = value;
}
get(): T {
return this.value;
}
}
const stringBox = new Box('hello');
const numberBox = new Box(123);// tsconfig.json
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"moduleResolution": "node",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": [
"src/**/*"
]
}