TypeScript
2026/1/16大约 3 分钟
TypeScript
基础类型
// 基本类型
let str: string = 'hello';
let num: number = 123;
let bool: boolean = true;
let n: null = null;
let u: undefined = undefined;
// 数组
let arr1: number[] = [1, 2, 3];
let arr2: Array<number> = [1, 2, 3];
// 元组
let tuple: [string, number] = ['hello', 123];
// 枚举
enum Color { Red, Green, Blue }
let c: Color = Color.Red;
// any / unknown
let any1: any = 'anything';
let unknown1: unknown = 'anything';
// void / never
function log(): void { console.log('log'); }
function error(): never { throw new Error(); }
// 对象
let obj: { name: string; age: number } = { name: 'Tom', age: 18 };接口
// 基本接口
interface User {
name: string;
age: number;
email?: string; // 可选属性
readonly id: number; // 只读属性
}
// 函数类型
interface SearchFunc {
(source: string, subString: string): boolean;
}
// 索引签名
interface StringArray {
[index: number]: string;
}
interface Dictionary {
[key: string]: any;
}
// 继承
interface Animal {
name: string;
}
interface Dog extends Animal {
breed: string;
}
// 实现
class MyDog implements Dog {
name = 'Buddy';
breed = 'Labrador';
}类型别名
// 基本类型别名
type ID = string | number;
type Point = { x: number; y: number };
// 联合类型
type Status = 'pending' | 'success' | 'error';
// 交叉类型
type Employee = Person & { employeeId: number };
// 条件类型
type IsString<T> = T extends string ? true : false;泛型
// 泛型函数
function identity<T>(arg: T): T {
return arg;
}
identity<string>('hello');
identity(123); // 类型推断
// 泛型接口
interface GenericIdentityFn<T> {
(arg: T): T;
}
// 泛型类
class GenericNumber<T> {
value: T;
add: (x: T, y: T) => T;
}
// 泛型约束
interface Lengthwise {
length: number;
}
function loggingIdentity<T extends Lengthwise>(arg: T): T {
console.log(arg.length);
return arg;
}
// 多个类型参数
function swap<T, U>(tuple: [T, U]): [U, T] {
return [tuple[1], tuple[0]];
}
// keyof
function getProperty<T, K extends keyof T>(obj: T, key: K) {
return obj[key];
}高级类型
// Partial:所有属性可选
type PartialUser = Partial<User>;
// Required:所有属性必选
type RequiredUser = Required<User>;
// Readonly:所有属性只读
type ReadonlyUser = Readonly<User>;
// Pick:选取部分属性
type UserName = Pick<User, 'name' | 'email'>;
// Omit:排除部分属性
type UserWithoutId = Omit<User, 'id'>;
// Record:构造对象类型
type PageInfo = Record<string, { title: string }>;
// Exclude:排除类型
type T = Exclude<'a' | 'b' | 'c', 'a'>; // 'b' | 'c'
// Extract:提取类型
type T = Extract<'a' | 'b' | 'c', 'a' | 'f'>; // 'a'
// NonNullable:排除 null 和 undefined
type T = NonNullable<string | null | undefined>; // string
// ReturnType:获取函数返回类型
type T = ReturnType<() => string>; // string
// Parameters:获取函数参数类型
type T = Parameters<(a: string, b: number) => void>; // [string, number]类型守卫
// typeof
function padLeft(value: string, padding: string | number) {
if (typeof padding === 'number') {
return ' '.repeat(padding) + value;
}
return padding + value;
}
// instanceof
class Bird { fly() {} }
class Fish { swim() {} }
function move(animal: Bird | Fish) {
if (animal instanceof Bird) {
animal.fly();
} else {
animal.swim();
}
}
// in
interface A { a: number }
interface B { b: string }
function test(x: A | B) {
if ('a' in x) {
console.log(x.a);
} else {
console.log(x.b);
}
}
// 自定义类型守卫
function isFish(pet: Fish | Bird): pet is Fish {
return (pet as Fish).swim !== undefined;
}类型断言
// as 语法
let value: any = 'hello';
let len: number = (value as string).length;
// 尖括号语法(JSX 中不能用)
let len: number = (<string>value).length;
// 非空断言
function getValue(x?: string) {
return x!.length; // 断言 x 不为 null/undefined
}
// const 断言
let arr = [1, 2, 3] as const; // readonly [1, 2, 3]
let obj = { name: 'Tom' } as const; // { readonly name: 'Tom' }模块
// 导出
export const name = 'module';
export default function() {}
export type { User };
// 导入
import { name } from './module';
import fn from './module';
import type { User } from './module';
// 命名空间
namespace Utils {
export function log(msg: string) {
console.log(msg);
}
}
Utils.log('hello');声明文件
// types.d.ts
declare module 'my-module' {
export function myFunction(): void;
}
// 全局变量
declare const VERSION: string;
// 全局函数
declare function greet(name: string): void;
// 扩展全局对象
declare global {
interface Window {
myProperty: string;
}
}配置文件
// tsconfig.json
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"lib": ["ES2020", "DOM"],
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"outDir": "./dist",
"rootDir": "./src",
"declaration": true,
"sourceMap": true
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}