深入浅出 TypeScript 函数和类

TypeScript 的函数和类是其最强大的特性之一,但如何理解这些概念呢?今天,我们要谈论的是 TypeScript 中的函数参数类型、返回值类型、箭头函数、函数重载、类的定义、继承等。

1. 函数参数类型

TypeScript 可以通过 : 指定函数参数的类型。

function add(num1: number, num2: number): number {
    return num1 + num2;
}

2. 返回值类型

TypeScript 也可以指定函数返回值的类型。

function getLength(str: string): number {
    return str.length;
}

3. 箭头函数

TypeScript 中也支持箭头函数,简化了函数定义的过程。

const add = (num1: number, num2: number) => num1 + num2;

4. 函数重载

TypeScript 支持函数重载,即一个函数可以有多个同名函数签名。

function add(num1: number, num2: number): number {
    return num1 + num2;
}

function add(str1: string, str2: string): string {
    return str1 + str2;
}

5. 类的定义

TypeScript 支持类的定义,包括属性和方法。

class Person {
    name: string;
    age: number;

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

    sayHello(): void {
        console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
    }
}

6. 继承

TypeScript 支持类的继承,子类可以继承父类的属性和方法。

class Animal {
    sound: string;

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

    makeSound(): void {
        console.log(this.sound);
    }
}

class Dog extends Animal {
    breed: string;

    constructor(breed: string, sound: string) {
        super(sound);
        this.breed = breed;
    }

    makeSound(): void {
        super.makeSound();
        console.log(`Woof! I'm a ${this.breed} dog.`);
    }
}

7. 访问修饰符

TypeScript 支持访问修饰符 public、private 和 protected。

class Person {
    public name: string;
    private age: number;

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

    public sayHello(): void {
        console.log(`Hello, my name is ${this.name}.`);
    }

    private sayAge(): void {
        console.log(`My age is ${this.age} years old.`);
    }
}

总之,通过本文,我们应该能够理解 TypeScript 中函数和类的各种特性和应用。


来源: 互联网
本文观点不代表源码解析立场,不承担法律责任,文章及观点也不构成任何投资意见。

赞 ()

相关推荐

发表回复

评论列表

点击查看更多

    联系我们

    在线咨询: QQ交谈

    微信:13450247865

    邮件:451255340#qq.com

    工作时间:周一至周五,9:30-18:30,节假日休息

    微信