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"?
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>
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With