Elysia Tools

在一个清晰的工作台里浏览工具、案例、可视化和主题指南。

热门分类

专题

语言
ZHDERUPTENFRES

Elysia Tools

导航

编程语言

TypeScript 示例

TypeScript代码示例,包含类型安全和Hello World演示

案例

这个案例集合中的条目

代码typescript简单

TypeScript Hello World

TypeScript Hello World程序和类型注解语法示例

难度

3/10

预计时间

15 min

标签

typescript, programming, types

前置条件

Basic JavaScript concepts

typescript
// TypeScript Hello World Examples

// 1. Basic Hello World with string type annotation
const message: string = "Hello, World!";
console.log(message);

// 2. Hello World function with type annotations
function sayHello(): string {
    return "Hello, World!";
}

console.log(sayHello());

// 3. Hello World with parameter types
function greet(name: string): string {
    return `Hello, ${name}!`;
}

console.log(greet("TypeScript"));
console.log(greet("World"));

// 4. Hello World with interface
interface Greeter {
    message: string;
    greet(): string;
}

class BasicGreeter implements Greeter {
    constructor(public message: string = "Hello, World!") {}
    
    greet(): string {
        return this.message;
    }
}

const greeter: Greeter = new BasicGreeter();
console.log(greeter.greet());

// 5. Hello World with union types
type Greeting = string | number;

function displayGreeting(greeting: Greeting): void {
    if (typeof greeting === 'string') {
        console.log(greeting);
    } else {
        console.log(`Greeting number: ${greeting}`);
    }
}

displayGreeting("Hello, World!");
displayGreeting(42);

// 6. Hello World with generic types
function createGreeting<T>(value: T): T {
    return value;
}

const stringGreeting: string = createGreeting<string>("Hello, World!");
const numberGreeting: number = createGreeting<number>(123);

console.log(stringGreeting);
console.log(numberGreeting);

// 7. Hello World with optional parameters
function personalizedGreeting(name: string, enthusiastic?: boolean): string {
    if (enthusiastic) {
        return `Hello, ${name}!!!`;
    }
    return `Hello, ${name}!`;
}

console.log(personalizedGreeting("Alice"));
console.log(personalizedGreeting("Bob", true));

// 8. Hello World with array types
const greetings: string[] = ["Hello", "Hola", "Bonjour", "こんにちは"];
greetings.forEach(greeting => console.log(`${greeting}, World!`));

// 9. Hello World with tuple types
const greetingInfo: [string, string, number] = ["Hello", "World", 2024];
console.log(`${greetingInfo[0]}, ${greetingInfo[1]}! (${greetingInfo[2]})`);

// 10. Hello World with enum types
enum GreetingType {
    Formal = "Good day",
    Casual = "Hello",
    Enthusiastic = "Hey"
}

function createGreetingByType(type: GreetingType, name: string): string {
    return `${type}, ${name}!`;
}

console.log(createGreetingByType(GreetingType.Formal, "World"));
console.log(createGreetingByType(GreetingType.Casual, "Everyone"));

// Basic data types with type annotations
const integer: number = 42;
const float: number = 3.14;
const text: string = "TypeScript";
const isActive: boolean = true;
const numbers: number[] = [1, 2, 3, 4, 5];
const person: { name: string; age: number } = { name: "John", age: 30 };

console.log(`Integer: ${integer}, Type: ${typeof integer}`);
console.log(`Text: ${text}, Type: ${typeof text}`);

// Type assertion
const someValue: any = "Hello, World!";
const strLength: number = (someValue as string).length;
console.log(`String length: ${strLength}`);

// Function with return type annotation
function addNumbers(a: number, b: number): number {
    return a + b;
}

console.log(`5 + 3 = ${addNumbers(5, 3)}`);

// Void function
function logMessage(message: string): void {
    console.log(message);
}

logMessage("This is a void function");

// Never type (function that never returns)
function throwError(message: string): never {
    throw new Error(message);
}

// Type inference (TypeScript can infer types)
let inferredString = "TypeScript infers this as string";
let inferredNumber = 100;

console.log(`Inferred string: ${inferredString}`);
console.log(`Inferred number: ${inferredNumber}`);
代码typescript中等

TypeScript 接口和类型

高级TypeScript接口、类型别名和工具类型

难度

7/10

预计时间

25 min

标签

typescript, types, interfaces

前置条件

Basic TypeScript syntax

typescript
// TypeScript Interfaces and Types Examples

// 1. Basic Interface
interface Person {
    name: string;
    age: number;
    email?: string;  // Optional property
    readonly id: number;  // Read-only property
}

const person: Person = {
    name: "Alice",
    age: 30,
    id: 1
};

// 2. Interface with methods
interface Vehicle {
    brand: string;
    model: string;
    start(): void;
    stop(): void;
}

class Car implements Vehicle {
    constructor(
        public brand: string,
        public model: string
    ) {}
    
    start(): void {
        console.log(`${this.brand} ${this.model} started`);
    }
    
    stop(): void {
        console.log(`${this.brand} ${this.model} stopped`);
    }
}

const myCar: Vehicle = new Car("Toyota", "Corolla");
myCar.start();
myCar.stop();

// 3. Interface extending
interface Animal {
    name: string;
    makeSound(): void;
}

interface Dog extends Animal {
    breed: string;
    wagTail(): void;
}

class Labrador implements Dog {
    constructor(
        public name: string,
        public breed: string = "Labrador"
    ) {}
    
    makeSound(): void {
        console.log("Woof!");
    }
    
    wagTail(): void {
        console.log("Tail wagging happily");
    }
}

const dog: Dog = new Labrador("Max");
dog.makeSound();
dog.wagTail();

// 4. Type Aliases
type ID = string | number;
type Coordinates = [number, number]; // Tuple type
type Status = "pending" | "completed" | "failed";

type User = {
    id: ID;
    name: string;
    status: Status;
    location: Coordinates;
};

const user: User = {
    id: "user123",
    name: "John Doe",
    status: "pending",
    location: [40.7128, -74.0060]
};

// 5. Generic Interfaces
interface Repository<T> {
    findById(id: string): T | null;
    save(entity: T): void;
    delete(id: string): boolean;
}

interface Product {
    id: string;
    name: string;
    price: number;
}

class ProductRepository implements Repository<Product> {
    private products: Product[] = [];
    
    findById(id: string): Product | null {
        return this.products.find(p => p.id === id) || null;
    }
    
    save(entity: Product): void {
        const existing = this.findById(entity.id);
        if (existing) {
            Object.assign(existing, entity);
        } else {
            this.products.push(entity);
        }
    }
    
    delete(id: string): boolean {
        const index = this.products.findIndex(p => p.id === id);
        if (index > -1) {
            this.products.splice(index, 1);
            return true;
        }
        return false;
    }
}

// 6. Utility Types
interface Book {
    id: string;
    title: string;
    author: string;
    price: number;
    published: boolean;
}

// Partial - makes all properties optional
type BookUpdate = Partial<Book>;

// Required - makes all properties required
type RequiredBook = Required<Book>;

// Pick - select specific properties
type BookInfo = Pick<Book, 'title' | 'author'>;

// Omit - remove specific properties
type BookWithoutPrice = Omit<Book, 'price'>;

// Record - create object type with specific keys and values
type BookCatalog = Record<string, Book>;

// 7. Function Types
type MathOperation = (a: number, b: number) => number;

const add: MathOperation = (a, b) => a + b;
const multiply: MathOperation = (a, b) => a * b;

console.log(`Add: ${add(5, 3)}`);
console.log(`Multiply: ${multiply(5, 3)}`);

// 8. Index Signatures
interface StringArray {
    [index: number]: string;
}

const names: StringArray = ["Alice", "Bob", "Charlie"];

interface Dictionary {
    [key: string]: number;
}

const ages: Dictionary = {
    "Alice": 30,
    "Bob": 25,
    "Charlie": 35
};

// 9. Mapped Types
type Optional<T> = {
    [P in keyof T]?: T[P];
};

type Readonly<T> = {
    readonly [P in keyof T]: T[P];
};

type ReadonlyBook = Readonly<Book>;

// 10. Conditional Types
type NonNullable<T> = T extends null | undefined ? never : T;

type ExtractType<T, U> = T extends U ? T : never;
type ExtractString = ExtractType<string | number | boolean, string>;

// Type predicates
function isString(value: any): value is string {
    return typeof value === 'string';
}

function processValue(value: any) {
    if (isString(value)) {
        console.log(`String value: ${value.toUpperCase()}`);
    } else {
        console.log(`Non-string value: ${value}`);
    }
}

processValue("hello");
processValue(42);

// 11. Declaration Merging
interface UserSettings {
    theme: string;
}

interface UserSettings {
    notifications: boolean;
}

const settings: UserSettings = {
    theme: "dark",
    notifications: true
};

// 12. Mixed types example
type ApiResponse<T> = {
    data: T;
    status: number;
    message: string;
};

interface ApiResponseHandler<T> {
    handleResponse(response: ApiResponse<T>): void;
}

class UserApiHandler implements ApiResponseHandler<User> {
    handleResponse(response: ApiResponse<User>): void {
        console.log(`User: ${response.data.name}, Status: ${response.status}`);
    }
}
代码typescript中等

TypeScript 类和高级OOP

TypeScript面向对象编程,包含类、继承和装饰器

难度

8/10

预计时间

30 min

标签

typescript, oop, classes

前置条件

Basic TypeScript syntax and interfaces

typescript
// TypeScript Classes and Advanced OOP Examples

// 1. Basic Class with Access Modifiers
class Employee {
    // Properties with access modifiers
    public id: number;
    private name: string;
    protected department: string;
    readonly company: string = "Tech Corp";

    constructor(id: number, name: string, department: string) {
        this.id = id;
        this.name = name;
        this.department = department;
    }

    // Public method
    public getDetails(): string {
        return `${this.name} (ID: ${this.id}) - ${this.department}`;
    }

    // Private method
    private calculateSalary(): number {
        return 50000 + (this.id * 1000);
    }

    // Protected method
    protected getDepartmentInfo(): string {
        return `Department: ${this.department}`;
    }
}

// 2. Class Inheritance
class Manager extends Employee {
    private teamSize: number;

    constructor(id: number, name: string, department: string, teamSize: number) {
        super(id, name, department);
        this.teamSize = teamSize;
    }

    public getManagerDetails(): string {
        return `${this.getDetails()} - Team Size: ${this.teamSize}`;
    }

    // Overriding method
    public getDetails(): string {
        return `${super.getDetails()} [MANAGER]`;
    }

    // Accessing protected member from parent
    public getFullInfo(): string {
        return `${this.getDetails()} - ${this.getDepartmentInfo()}`;
    }
}

const manager = new Manager(1, "Alice", "Engineering", 10);
console.log(manager.getManagerDetails());

// 3. Abstract Classes
abstract class Shape {
    constructor(protected color: string) {}

    abstract getArea(): number;
    abstract getPerimeter(): number;

    public getColor(): string {
        return this.color;
    }

    public printInfo(): void {
        console.log(`Shape color: ${this.color}`);
    }
}

class Circle extends Shape {
    constructor(
        color: string,
        private radius: number
    ) {
        super(color);
    }

    getArea(): number {
        return Math.PI * this.radius * this.radius;
    }

    getPerimeter(): number {
        return 2 * Math.PI * this.radius;
    }
}

class Rectangle extends Shape {
    constructor(
        color: string,
        private width: number,
        private height: number
    ) {
        super(color);
    }

    getArea(): number {
        return this.width * this.height;
    }

    getPerimeter(): number {
        return 2 * (this.width + this.height);
    }
}

const circle = new Circle("red", 5);
const rectangle = new Rectangle("blue", 4, 6);

// 4. Static Members
class MathHelper {
    private static PI: number = 3.14159;

    public static calculateCircleArea(radius: number): number {
        return this.PI * radius * radius;
    }

    public static calculateCircleCircumference(radius: number): number {
        return 2 * this.PI * radius;
    }

    public static getVersion(): string {
        return "1.0.0";
    }
}

console.log(`Circle area: ${MathHelper.calculateCircleArea(5)}`);
console.log(`MathHelper version: ${MathHelper.getVersion()}`);

// 5. Getters and Setters
class BankAccount {
    private _balance: number = 0;

    get balance(): number {
        return this._balance;
    }

    set balance(amount: number) {
        if (amount < 0) {
            throw new Error("Balance cannot be negative");
        }
        this._balance = amount;
    }

    public deposit(amount: number): void {
        if (amount > 0) {
            this._balance += amount;
        }
    }

    public withdraw(amount: number): void {
        if (amount > 0 && amount <= this._balance) {
            this._balance -= amount;
        }
    }
}

const account = new BankAccount();
account.balance = 1000;
console.log(`Account balance: ${account.balance}`);

// 6. Implementing Multiple Interfaces
interface Loggable {
    log(): void;
}

interface Serializable {
    serialize(): string;
}

class User implements Loggable, Serializable {
    constructor(
        public id: number,
        public name: string,
        public email: string
    ) {}

    log(): void {
        console.log(`User: ${this.name} (${this.email})`);
    }

    serialize(): string {
        return JSON.stringify({
            id: this.id,
            name: this.name,
            email: this.email
        });
    }

    static deserialize(data: string): User {
        const obj = JSON.parse(data);
        return new User(obj.id, obj.name, obj.email);
    }
}

const user = new User(1, "John Doe", "john@example.com");
user.log();
const serialized = user.serialize();
console.log(`Serialized: ${serialized}`);

// 7. Class Decorators
function sealed(constructor: Function) {
    Object.seal(constructor);
    Object.seal(constructor.prototype);
}

@sealed
class SealedClass {
    constructor(public message: string) {}
}

// Property Decorator
function format(formatString: string) {
    return function (target: any, propertyKey: string) {
        let value: string;
        
        const getter = function() {
            return value;
        };
        
        const setter = function(newVal: string) {
            value = formatString.replace(/{0}/g, newVal);
        };
        
        Object.defineProperty(target, propertyKey, {
            get: getter,
            set: setter,
            enumerable: true,
            configurable: true
        });
    };
}

class GreetingService {
    @format("Hello, {0}!")
    private name: string = "";

    constructor(name: string) {
        this.name = name;
    }

    public getGreeting(): string {
        return this.name;
    }
}

const greeting = new GreetingService("World");
console.log(greeting.getGreeting()); // "Hello, World!"

// 8. Mixins
class Timestamped {
    private timestamp: number = Date.now();

    public getTimestamp(): number {
        return this.timestamp;
    }
}

class Activatable {
    private isActive: boolean = false;

    public activate(): void {
        this.isActive = true;
    }

    public deactivate(): void {
        this.isActive = false;
    }

    public getActiveStatus(): boolean {
        return this.isActive;
    }
}

// Apply mixins
interface SmartObject extends Timestamped, Activatable {}

class SmartObject {
    public getTimestamp!: () => number;
    public activate!: () => void;
    public deactivate!: () => void;
    public getActiveStatus!: () => boolean;

    constructor(public id: string, public name: string) {}
}

// Apply mixin functionality
Object.assign(SmartObject.prototype, Timestamped.prototype, Activatable.prototype);

const smartObj = new SmartObject("obj1", "Smart Device");
console.log(`Timestamp: ${smartObj.getTimestamp()}`);
smartObj.activate();
console.log(`Active: ${smartObj.getActiveStatus()}`);

// 9. Generic Classes
class Container<T> {
    private items: T[] = [];

    public addItem(item: T): void {
        this.items.push(item);
    }

    public removeItem(item: T): boolean {
        const index = this.items.indexOf(item);
        if (index > -1) {
            this.items.splice(index, 1);
            return true;
        }
        return false;
    }

    public getItems(): T[] {
        return [...this.items];
    }

    public findItem(predicate: (item: T) => boolean): T | undefined {
        return this.items.find(predicate);
    }
}

const stringContainer = new Container<string>();
stringContainer.addItem("Hello");
stringContainer.addItem("World");
console.log(stringContainer.getItems());

// 10. Singleton Pattern
class DatabaseConnection {
    private static instance: DatabaseConnection;
    private connection: any;

    private constructor() {
        this.connection = "Database connection established";
    }

    public static getInstance(): DatabaseConnection {
        if (!DatabaseConnection.instance) {
            DatabaseConnection.instance = new DatabaseConnection();
        }
        return DatabaseConnection.instance;
    }

    public query(sql: string): void {
        console.log(`Executing: ${sql}`);
        console.log(`Using: ${this.connection}`);
    }
}

const db1 = DatabaseConnection.getInstance();
const db2 = DatabaseConnection.getInstance();
console.log(`Same instance: ${db1 === db2}`);
db1.query("SELECT * FROM users");

工具

经常与该案例搭配使用的工具

相关内容

相关案例集合

相关内容

相关专题

专题

JSON 到强类型代码生成器

从 JSON 或 schema 证据生成 TypeScript、Go、Rust、Kotlin、Java、C# 与 Zod 校验模型。

专题

药代动力学教学模型与结果核查

用于教学或 QA 的药代公式、模型假设和结果一致性核查,不提供用药剂量、诊断或临床建议。

专题

OpenAPI 实用工作流

从 OpenAPI 生成类型与文档,审查破坏性变更,校验响应,并用压力与变异测试加固契约。

专题

经典与现代密码工具

在安全的教学或 CTF 场景中比较可逆的经典变换与现代加密,并明确玩具密码不等于安全防护。

首页
工具3212
案例593
可视化471
文件查看器103
专题239
标签333
图像、音频与视频657

图像、音频、视频处理、转换与优化工具

数学、日期与金融647

计算器、数值计算、日期逻辑、统计与金融工具

设计与颜色298

颜色、版式、图形、视觉样式与设计辅助工具

文本与写作209

写作、清洗、格式化、提取与文本分析工具

开发与 Web193

开发者工具、网络处理、Web 调试与自动化辅助工具

转换与编码175

格式、文件、压缩包、单位与编码转换工具

潜客测验发布与联系人交接
讣告、悼词与纪念卡的家属复核及交付
本地习惯记录的备份、恢复演练与分享前检查
长文改编 X 串文与 LinkedIn 帖子的事实复核与交付
Markdown 互动课件审校、离线演示与交付

© 2026 Elysia Tools. 保留所有权利。

文档价格关于我们服务条款隐私政策Cookie 政策联系我们

Development

JSON 转 TypeScript

将 JSON 数据转换为 TypeScript interface 或 type,支持联合类型、可选字段与嵌套对象推断

Development

OpenAPI 转 TypeScript 类型生成器

将 OpenAPI 或 Swagger 的 JSON/YAML 规范转换为 TypeScript 接口类型、请求参数类型和响应类型,并支持输出格式与命名风格配置

编程语言

C++ 示例

C++ 代码示例和Hello World演示

编程语言

Go 示例

Go (Golang) 代码示例和Hello World演示

编程语言

Java 示例

Java代码示例和Hello World演示

编程语言

JavaScript 示例

JavaScript代码示例和Hello World演示

编程语言

Python 示例

Python代码示例和Hello World演示

编程语言

Scala 语言示例

Scala编程示例和函数式编程概念