收集、管理和分享有用的代码片段,提高开发效率
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());
通用响应类型
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' });
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
类方法装饰器
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
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
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());
高效管理您的代码片段,提高开发效率
通过关键字、语言或分类快速查找代码片段,支持模糊搜索和过滤功能
支持多种编程语言的语法高亮,使代码更加清晰易读
随时随地访问您的代码片段库,支持桌面和移动设备
浏览最受欢迎的代码分类