Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix typescript "Property does not exist on type" with union types?

Tags:

typescript

I am trying to access a property of a variable that might or might not be an object. If the variable is an object I want to read its "value" property, otherwise just read the variable.

I want to do something like this:

interface MyType {
    myvar: string | MyObject
}
interface MyObject {
    value: string
}

function MyComponent({myvar}: MyType){
    return(
        <div>
            {myvar.value? myvar.value : myvar}
        </div>
    )
}

But I get the error "Property 'value' not found on type MyObject" on myvar.value.

I have tried checking if the variable is an object{typeof myvar === "object" ? myvar.value : myvar} , with no luck.

I have found this typescript issue https://github.com/Microsoft/TypeScript/issues/28138 where they suggest using if("value" in myvar) or if(myvar.value !== undefined).

Unfortunately it did not work.

EDIT: is there a solution that doesn't require casting to "any"?

like image 673
asile Avatar asked Oct 15 '22 11:10

asile


2 Answers

you could try something like:

const getValueType = (myvar: any) => {
   if (myvar typeof === "object") {
      return myvar.value
   } else {
     return myvar
   }
}

or this: 

const getValueType = (myvar: any) => {
   (myvar typeof === "object") ? myvar.value : myvar
}

render(){
  const value = getValueType(myvar)
  <div>
      {value}
  </div>
}
like image 123
Mitch Kroska Avatar answered Oct 20 '22 05:10

Mitch Kroska


I found a slightly better solution than casting to any. Cast to the type that does contain the value property.

interface MyType {
    myvar: string | MyObject
}
interface MyObject {
    value: string
}

function MyComponent({myvar}: MyType){
    return(
        <div>
            {(myvar as MyObject).value? (myvar as MyObject).value : myvar}
        </div>
    )
}

as described here https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-differentiating-types

like image 29
asile Avatar answered Oct 20 '22 05:10

asile