代码片段仓库

收集、管理和分享有用的代码片段,提高开发效率

代码片段

TS类 TypeScript

TypeScript类示例

class Person {
  private name: string;
  age: number;
  
  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }
  
  describe(): string {
    return `${this.name} is ${this.age} years old`;
  }
}

const alice = new Person('Alice', 30);
console.log(alice.describe());
TS泛型 TypeScript

通用响应类型

interface ApiResponse<T> {
  data: T;
  error?: string;
  status: number;
}

function createResponse<T>(
  data: T, 
  error?: string,
  status: number
): ApiResponse<T> {
  return { data, error, status };
}

let userResponse: ApiResponse<{name: string}> = createResponse({ name: 'John' });
JS模块 JavaScript

ES6模块导出

// math.js
export const PI = 3.14159;

export function add(a, b) {
  return a + b;
}

export default function multiply(a, b) {
  return a * b;
}

// app.js
import PI, { add } from './math.js';
import multiply from './math.js';

console.log(PI); // 3.14159
console.log(add(2, 3)); // 5
console.log(multiply(4, 5)); // 20
TS装饰器 TypeScript

类方法装饰器

function logger(target: any, name: string, descriptor: PropertyDescriptor): void {
  const original = descriptor.value;
  if (typeof original === 'function') {
    descriptor.value = function (..args: any[]) {
      console.log('Called ' + name + ' with ', args);
      const result = original.apply(this, args);
      console.log('Result: ', result);
      return result;
    };
  }
}

class Calculator {
  @logger
  add(x: number, y: number): number {
    return x + y;
  }
}

const calc = new Calculator();
console.log(calc.add(2, 3)); // Logs to console, returns 5
JS模块 JavaScript

ES6模块导出

// math.js
export const PI = 3.14159;

export function add(a, b) {
  return a + b;
}

export default function multiply(a, b) {
  return a * b;
}

// app.js
import PI, { add } from './math.js';
import multiply from './math.js';

console.log(PI); // 3.14159
console.log(add(2, 3)); // 5
console.log(multiply(4, 5)); // 20
TS类 TypeScript

TypeScript类示例

class Person {
  private name: string;
  age: number;
  
  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }
  
  describe(): string {
    return `${this.name} is ${this.age} years old`;
  }
}

const alice = new Person('Alice', 30);
console.log(alice.describe());

为什么选择CodeSnippets?

高效管理您的代码片段,提高开发效率

智能搜索

通过关键字、语言或分类快速查找代码片段,支持模糊搜索和过滤功能

语法高亮

支持多种编程语言的语法高亮,使代码更加清晰易读

多设备同步

随时随地访问您的代码片段库,支持桌面和移动设备

热门分类

浏览最受欢迎的代码分类