Validating for the existence of a property in Typescript

My function is able to accept two different types of objects as arguments

myFunc(arg: (Obj1 | Obj2))

Within my function, I am trying to achieve the following:

let val = ( arg instance of Obj1 ) ? Obj1.propOnlyOnObj1 : Obj2.propOnlyOnObj2;

However, TypeScript throws errors because these properties exist only on one of the object types.

Answer №1

This solution should do the trick

class X {
    public val1: string = 'abc';
}

class Y {
    public val2: number = 123;
}

function example(input: X | Y) {
    var result = input instanceof X ? input.val1 : input.val2;
    // utilize result
}

Feel free to experiment with it here: Typescript playground

Answer №2

Utilizing the lodash.has method:

const value = _.has(Object1, 'propOnlyOnObj1') ?
    Object1.propOnlyOnObj1 : Object2.propOnlyOnObj2;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to pass a generic interface to the zustand create function in a TypeScript environment

Having trouble figuring out the right syntax to pass a generic interface when calling a function that accepts a generic type. My goal is to use: const data = itemStore<T>(state => state.data) import { create } from "zustand"; interface ...

What is the best way to outline this model using typescript?

Here is a JSON model that I am working with: { "loggers" : { "logger1" : { "name" : "logger1", "level" : "DEBUG", "sub_loggers" :{ "logger1.nested_logger1" : { "name": "lo ...

Exploring the money library in typescript after successfully installing it on my local machine

I've been struggling to set up a new library in my TypeScript project for the first time, and I can't seem to get it functioning properly. The library in question is money. I have downloaded it and placed it in the root of my project as instructe ...

In the latest version of Angular, accessing document.getelementbyid consistently returns null

I am struggling with a component that looks like this export class NotificationPostComponent extends PostComponent implements OnInit, AfterViewInit { commentsDto: IComment[] = []; commentId = ''; ngOnInit(): void { this.route.data ...

Finding out whether the current date falls between a startDate and endDate within a nested object in mongoose can be done by using a specific method

My data structure includes a nested object as shown: votingPeriod: {startDate: ISOdate(), endDate: ISOdate()}. Despite using the query below, I am getting an empty object back from my MongoDB. const organizations = await this.organizationRepository.find( ...

A more efficient method for handling exceptions when the return type is a promise

What is the most effective method for specifying the return type of an asynchronous operation that returns a promise or an Error? Does the code snippet below seem logical to you? public async findUserByUsername(username: string, context: IDataContext): P ...

Creating Multiple Routes in a Single TypeScript and AngularJS Route File

I have built a module with TypeScript and AngularJS that includes multiple pages. I would like to use one TypeScript controller per page. How can I define multiple controllers in my routes? Currently, I have only defined one, but what if I have 6 or 7 co ...

How can one overcome CORS policies to retrieve the title of a webpage using JavaScript?

As I work on a plugin for Obsidian that expands shortened urls like bit.ly or t.co to their full-length versions in Markdown, I encounter a problem. I need to fetch the page title in order to properly create a Markdown link [title](web link). Unfortunatel ...

Error: TypeError encountered during UI Runtime JSON conversion of Circular Data Structure

I'm facing an issue while attempting to parse and stringify certain JSON data. The error occurs on this specific line of code: this.copyOfColumns = JSON.parse(JSON.stringify(Object.assign([], this.columns))); Below is the complete @Input (using Ang ...

Incorporating a skeletal design effect into a table featuring sorting and pagination options

Is there a way to implement the Skeleton effect in a MUI table that only requires sorting and pagination functionalities? I tried using the 'loading' hook with fake data fetching and a 3-second delay, but it doesn't seem to work with DataGri ...

Tips for retrieving a reactive variable from a setup() method?

I'm currently working on a small notes app and using Vue3 + Typescript to enhance my skills. The following code snippet demonstrates how to dynamically create and display an Array of notes: <template> <q-layout> <div v-for ...

Is there a method we can use to replace fixture fields with data created during the test case to produce a dynamic payload? (Already attempted existing solution)

I am new to using Cypress and I'm wondering if there is a way to generate a dynamic payload by replacing values in a JSON file with values generated programmatically in a Cypress test. This is similar to what we do in Rest Assured by substituting %s i ...

The error message "Undefined value received instead of a string or boolean in Vuetify and nuxt.js rules" indicates that the expected data type was not provided

I recently created an app at my workplace and encountered an error in the text area similar to what I have described in my title. After researching the issue online, I found some information but still struggle to fully grasp the concept. My objective is t ...

Is it considered an anti-pattern in TypeScript to utilize BehaviorSubject for class or object properties?

When working with Angular, I find myself frequently displaying members of classes in an Angular HTML template. These classes often share common members structured like this: class Foo { bar: string; bas: Date; } There are instances where I need to ...

The console.log() function is throwing an error message, saying, "Cannot read properties of undefined (reading 'log')"

I'm currently working on a NestJS application and running into an issue with the console.log function. No matter what I input, I keep getting this error: [Nest] 71101 - 04/03/2023, 2:14:45 PM ERROR [ExceptionsHandler] Cannot read properties of unde ...

Tips for distributing a Vue plugin on NPM

I developed a straightforward plugin for Voca.js using Typescript. The source code can be found here. index.ts import VueVoca from './vue-voca'; export { VueVoca }; vue-voca.ts import vue from 'vue'; export default { install( ...

Upgrade from using fetch to utilize await in order to achieve the same outcome

After transitioning a one-time fetch request code snippet to my API, I encountered the following: let response = await fetch(visitURL, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization& ...

Challenges with incorporating asynchronously fetched data in component operations

I have encountered an issue where the data retrieved from a server in a service is available in the component's template but not in the actual code. This seems strange to me. I made the call in the ngOnInit method of my main AppComponent ngOnInit() { ...

React and TypeScript integration with react-router presents a challenge with handling state parameters

Hello, I'm currently working with React using TypeScript and React Router. I've encountered an issue regarding navigation to the filterParam. When I make my first call, the URL in the browser tab shows "?filter=" before calling Navigate(). Howeve ...

Chai-as-promised avoids errors in TypeScript test cases

I am attempting to utilize chai-as-promised in my Mocha test for some TypeScript code, but I am having trouble with the syntax. To troubleshoot, I set up a minimal reproducer: index.ts // Sample promise that resolves on red, fails on other values export co ...