zoukankan      html  css  js  c++  java
  • [Typescript] “Required” Mapped Type, +/- Modifiers

    For example we have interface:

    interface Person {
      name: string,
      age?: number  
    }

    'age' is an optional prop.

    // will have an error since person.age is used
    function printAge(person) {
      return `${person.name} is ${person.age}`
    }
    
    const person = {
        name: "wan'
    }
    
    printAge(person)

    Required type:

    type MyRequired<T> = {
        [P inkeyof T]-?: T[P]
    }

    '-?': remove optional modifier so it become required prop.

    function printAge(person: MyRequired<Person>) {
      return `${person.name} is ${person.age}`
    }
    
    const person: MyRequired<Person> = {
        name: "wan',
        age: 23
    }
    
    printAge(person)

    or can use built-in:

    function printAge(person: Required<Person>) {
      return `${person.name} is ${person.age}`
    }
    
    const person: Required<Person> = {
        name: "wan',
        age: 23
    }
    
    printAge(person)
  • 相关阅读:
    <O(n),O(1)>的LCA
    hdu6110
    ACM模板
    prufer编码
    UvaLive6893_The_Big_Painting
    HDU5669
    Codeforces786B
    二分图部分总结
    Git简介和Windows下安装步骤
    笔记本电脑插入耳机后无法使用解决办法
  • 原文地址:https://www.cnblogs.com/Answer1215/p/13758747.html
Copyright © 2011-2022 走看看