Home > Mobile >  Property does not exist on conditional custom type
Property does not exist on conditional custom type

Time:06-17

I have a type representing the object that gets passed in as a function's parameters. I want the function to do different things based on if one property or the other property was in that object. Here's an example:

type FooOrBar = { foo: string } | { bar: string }
function doSomething(obj: FooOrBar) {
  const { foo, bar } = obj
  
  if (foo) {
    // do something and then return early
  }

  if (bar) {
    // do something and then return early
  }

  // throw an error if neither foo nor bar was present
}

However, I get a Typescript error when I try to destructure foo and bar: "Property foo does not exist on type FooOrBar." (and the same for bar). Destructuring in the function parameters doesn't help. What is the best way to rewrite this to satisfy TS?

CodePudding user response:

As the property bar is not even optional but not present at all, this is not allowed in typescript. Instead, you could work with optional properties:

type FooOrBar = {
  foo?: string,
  bar?: string
}

This should be allowed and both properties are always present (but optional) on the object.

CodePudding user response:

Typescript will throw an error because there can never be a case when both foo and bar are in the object. You cannot destructure a property which does not exist when using TypeScript.

Using the same union opertaor, you can use the in operator though:

type FooOrBar = { foo: string } | { bar: string }
function doSomething(obj: FooOrBar) {
  
  if ('foo' in obj) {
    // do something and then return early
  }

  else if ('bar' in obj) {
    // do something and then return early
  }

  // throw an error if neither foo nor bar was present
}

Link

  • Related