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
}
More Related Contents:
- Transform union type to intersection type
- Type union not checking for excess properties
- ‘any’ vs ‘Object’
- Create a global variable in TypeScript
- Get an object’s class name at runtime
- How to convert a string to number in TypeScript?
- How to use jQuery with TypeScript
- Way to tell TypeScript compiler Array.prototype.filter removes certain types from an array?
- Type definition in object literal in TypeScript
- Difference between Variance, Covariance, Contravariance and Bivariance in TypeScript
- Confusing “duplicate identifier” Typescript error message
- How do I declare object value type without declaring key type?
- Angular2 canActivate() calling async function
- Purpose of declare keyword in TypeScript
- Keyof inferring string | number when key is only a string
- How to install Typescript typings for google maps
- Function property vs method
- How to declare a type as nullable in TypeScript?
- What TypeScript version is Visual Studio Code using? How to update it?
- Why does TypeScript track mutation of function static properties?
- Array VS Type[] in Typescript
- TypeScript filter out nulls from an array
- typescript: validate excess keys on value, returned from function
- Typescript: Omit a property from all interfaces in a union, but keep the union structure
- Declaring abstract method in TypeScript
- How to update TypeScript to latest version with npm?
- What is a TypeScript Map file?
- Typescript: Spread types may only be created from object types
- Why TypeScript lets me add a string and a number? Can I prevent it?
- A way to mark arbitrary strings in Typescript Template Literals