• TypeScript中extends的用法


    介绍

    extends 关键字在 TypeScript 中有多种应用,包括泛型约束、继承类、接口继承和条件类型。通过灵活使用 extends,TypeScript 提供了丰富的工具来增强类型安全性,使代码更具表现力和可维护性。

    1. 约束接口的继承
    extends 关键字也可用于接口。通过接口继承,我们可以创建一个继承另一个接口的新接口,并添加额外的属性或方法。

    interface Person {
     name: string;
     age: number;
    }
    
    interface Employee extends Person {
     employeeId: number;
    }
    
    const employee: Employee = {
     name: "John",
     age: 30,
     employeeId: 12345
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    2. 约束类的继承
    在 TypeScript 中,extends 关键字也用于类的继承。子类可以继承父类的属性和方法,并在需要时进行重写。

    class Animal {
      name: string;
    
      constructor(name: string) {
        this.name = name;
      }
    }
    
    class Dog extends Animal {
      breed: string;
    
      constructor(name: string, breed: string) {
        super(name);
        this.breed = breed;
      }
    }
    
    const myDog = new Dog("Fido", "Golden Retriever");
    console.log(myDog.name); // 访问父类属性
    console.log(myDog.breed); // 访问子类属性
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    3. 约束泛型类型参数
    在 TypeScript 中,泛型(generics)使我们能够编写可重用的函数、类和组件,同时保持类型的安全性。extends 关键字在泛型中常常用于约束泛型类型参数,以确保传入的类型符合某些要求。

    function lengthOfArray<T>(arr: T[]): number {
     return arr.length;
    }
    
    const numbers = [1, 2, 3];
    const result = lengthOfArray(numbers);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    在上面的示例中,T 是泛型类型参数,它可以是任何类型。但有时我们希望泛型参数必须是某种类型的子类型。这时可以使用 extends 关键字来添加约束:

    function firstElement<T extends Array<any>>(arr: T): T[0] {
      return arr[0];
    }
    
    const numbers = [1, 2, 3];
    const firstNum = firstElement(numbers); // firstNum 的类型是 number
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    表示 T 必须是 Array 或其子类型。这确保了传入的参数 arr 是一个数组,从而允许我们安全地访问其第一个元素。

    4.条件类型
    在 TypeScript 2.8+ 中,extends 关键字还被用于条件类型。条件类型使我们能够基于类型参数的属性来确定最终的类型。

    type NonNullable<T> = T extends null | undefined ? never : T;
    
    const x: string | null = "hello";
    const y: string = x; // 编译通过
    
    const a: string | null = null;
    const b: string = a; // 报错
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    在上述示例中,NonNullable 是一个条件类型,它检查泛型类型 T 是否是 null 或 undefined,如果是,则返回 never 类型,否则返回 T 类型。这允许我们确保某个值不会为 null 或 undefined。

  • 相关阅读:
    【代码随想录】算法训练计划13
    数据结构-双向链表
    音视频开发—音频相关概念:数模转换、PCM数据与WAV文件详解
    (工厂+策略)实现登录功能
    wy的leetcode刷题记录_Day43
    计算机毕业设计Java教师业绩考核和职称评审系统(源码+系统+mysql数据库+lw文档)
    JavaSE:String类
    Ubuntu下Nginx配置ModSecurity详细思路及过程
    全息网御上榜《CCSIP 2022中国网络安全产业全景图》
    【数据结构】堆和优先级队列
  • 原文地址:https://blog.csdn.net/CYL_2021/article/details/133975099