简体   繁体   中英

How can I narrow a type such that a field is no longer optional

I have a type that has an optional field but I want to be able to return a similar type where that field isn't optional. eg

type Foo = {
  x?: string
}
type Bar = {x: string}

const fn = (foo: Foo): Bar => {
  if (foo.x) {
    return foo
  }

  throw new Error
}

however, this doesn't type check because foo isn't narrowed to Bar . Can this be solved without a cast?

typescript play

Because the argument could be mutated somewhere else later it's a bad idea to narrow it in this case. Instead it's better to return a copy.

type Foo = {
  x?: string
}
type Bar = {x: string}

const fn = (foo: Foo): Bar => {
  if (foo.x) {
    return {x: foo.x}
  }

  throw new Error
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM