HsuMoonHao HsuMoonHao
首页
  • 前端文章

    • JavaScript
    • 数据结构与算法
  • vue3相关

    • 《JavaScript教程》
GitHub (opens new window)

HsyMoonHao

前端界的小学生
首页
  • 前端文章

    • JavaScript
    • 数据结构与算法
  • vue3相关

    • 《JavaScript教程》
GitHub (opens new window)
  • typescript utils
    • Async和Defer
    • utils
    HsyMoonHao
    2023-12-23
    目录

    typescript utils

    # 1. 类型中的可选属性改成必选属性

      // 假设我们有个如下这样的一个类型Employee, 其中的name和salary是可选的;
      interface Employee {
        id: number;
        name?: string;
        salary?: number;
      }
    
      type withRequiredProperty<Type, key extends keyof Type> = Type & {
        [Property in key]-?: Type[Property];
      };
    
      // 这样我们就可以将可选属性修改为必选属性了
      const employee: withRequiredProperty<Employee, 'name' | 'salary'> = {
        id: 1,
        name: 'John',
        salary: 5000
      };
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17

    注:-?语法称为映射修饰符 (opens new window),用于影响可选属性

    使用typescript内置的Required类型也可以使得所有属性都变成必选属性;

      interface Employee {
        id?: number;
        name?: string;
        salary?: number;
      }
    
      const employee = Required<Employee>{
        id: 1,
        name: 'John',
        salary: 5000
      }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    编辑 (opens new window)
    #utils#typescript
    上次更新: 2023/12/23, 14:47:23
    Async和Defer

    Async和Defer→

    最近更新
    01
    Async和Defer
    01-03
    02
    对SPA的理解
    05-29
    03
    react中的生命周期函数
    05-22
    更多文章>
    Theme by Vdoing | Copyright © 2023-2024 HsyMoonHao | MIT License
    • 跟随系统
    • 浅色模式
    • 深色模式
    • 阅读模式