Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript property does not exist on union type

Tags:

typescript

This is a situation I have ran into a couple of times, it seems like it should be fairly straightforward, but I can't find a solution that doesn't set the type to any

A function takes one of two different objects as the argument, checks which object has been received, and returns the corresponding field.

This is a simplified version of the problem, but the issue is that the two objects are only distinguishable by their properties(which have no overlap), and I can't access any of the properties, because they're not present on the other type.

type Obj1 = {   message: string }  type Obj2 = {   text: string }  const getText = (obj: Obj1 |obj2): string => {   if (obj.message) {     return obj.message   }    return obj.text } 
like image 823
PeterN Avatar asked Nov 21 '19 12:11

PeterN


People also ask

Does not exist on type Union TypeScript?

The "property does not exist on type union" error occurs when we try to access a property that is not present on every object in the union type. To solve the error, use a type guard to ensure the property exists on the object before accessing it.

How do you handle a union type in TypeScript?

TypeScript Union Type Narrowing To narrow a variable to a specific type, implement a type guard. Use the typeof operator with the variable name and compare it with the type you expect for the variable.

Does not exist on type TypeScript?

The "Property does not exist on type '{}'" error occurs when we try to access or set a property that is not contained in the object's type. To solve the error, type the object properties explicitly or use a type with variable key names.

How do you declare a union type variable in TypeScript?

TypeScript 1.4 gives programs the ability to combine one or two types. Union types are a powerful way to express a value that can be one of the several types. Two or more data types are combined using the pipe symbol (|) to denote a Union Type.


1 Answers

You have to narrow down the type. You can do so by using the in operator.

const getText = (obj: Obj1 | Obj2): string => {   if ("message" in obj) {     return obj.message   }    return obj.text } 
like image 132
Murat Karagöz Avatar answered Oct 08 '22 01:10

Murat Karagöz