[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)

 

posted @ 2020-10-01 18:50  Zhentiw  阅读(124)  评论(0编辑  收藏  举报