There is no union property present on this union type

I am facing an issue with TypeScript:

type Foo = {
  a: number
}

type Bar = {
  b: number
}

type Props = {
  object?: Foo | Bar | null;
  keys?: (keyof Foo)[] | (keyof Bar)[];
}

function myFunction({ object, keys = ['a'] }: Props) {
  const values = keys.map(key => object && object[key]);
  // Element implicitly has an 'any' type because expression of type '"a" | "b"' can't be used to index type 'Foo | Bar'.
  // Property 'b' does not exist on type 'Foo | Bar'.
}

What approach would you take to define types for a situation where the inputs can be either of type Foo or Bar?

I am working on creating an abstraction that can accept two objects and specific keys to extract from those objects. The input objects could be of type A or C. They may have varying keys, but the user is expected to provide the corresponding keys based on the object passed.

Answer №1

Props can be improved by specifying the props of Foo and Bar separately.

You could implement a generic solution like this:

type Props<T> = {
  object?: T | null;
  keys?: (keyof T)[];
};

function myFunction<T extends Foo | Bar>({ object, keys = ['a'] as (keyof T)[] }: Props<T>) {
  const values = keys.map(key => object && object[key]);
}

If you plan on returning something from this function, consider tightening your API to avoid requiring users to perform additional checks.

Answer №2

My recommendation would be to use a discriminated union.

type Car = {
 type: "car";
 doors: number
}

type Truck = {
  type: "truck";
  payload: number
}

type Vehicle = Car | Truck;

function calculateValue(vehicle: Vehicle) {
  const result = vehicle.type == "car"? vehicle.doors : vehicle.payload;
}

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

Is it considered beneficial to use Observable as a static class member?

Lately, I have been diving into a new Angular project and noticed that the common way to share state between unrelated components is by using rxjs Subject/BehaviorSubject as static members within the class. For instance: export class AbcService { privat ...

What is the best way to incorporate sturdy data types into the alternative function for this switch statement

const switchcase = (value, cases, defaultCase) => { const valueString = String(value); const result = Object.keys(cases).includes(valueString) ? cases[valueString] : defaultCase; return typeof result === 'function' ? result() : r ...

Verifying TypeScript Class Instances with Node Module Type Checking

My current task involves converting our Vanilla JS node modules to TypeScript. I have rewritten them as classes, added new functionality, created a legacy wrapper, and set up the corresponding Webpack configuration. However, I am facing an issue with singl ...

Issue: This error occurs when attempting to double click on the diagram or a node but the show function for c is not recognized

I've encountered an issue with my gojs diagram. When I double click on it to edit the node name, I receive an error message. This problem occurred after upgrading my gojs version from v1.7.14 to v2.2.17. Below is the error stack trace: core.mjs:8453 E ...

Fatal error: The main module could not be located. Please check the path `/src/test.ts` for resolution errors

I am encountering an issue while trying to execute the unit test for my Angular 2 Application using ng test. The error message I keep receiving is: ERROR in Entry module not found: Error: Can't resolve '/Users/username/Dev/dashboard/src/test.t ...

Dealing with asynchronous operations in a pipeline with fp-ts

I'm currently exploring fp-ts and have been contemplating how to restructure my functions in order to steer clear of nested folds. While many online examples showcase a clean invocation of the pipe function, I am struggling to eliminate the nested fol ...

Exploring Function Overriding in TypeScript

Currently, I'm working on developing a TypeScript method. import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable({ p ...

Trouble arises when trying to import Jest with Typescript due to SyntaxError: Import statement cannot be used outside a module

Whenever I execute Jest tests using Typescript, I encounter a SyntaxError while importing an external TS file from a node_modules library: SyntaxError: Cannot use import statement outside a module I'm positive that there is a configuration missing, b ...

When implementing JSS with React and TypeScript, certain CSS properties may encounter a `type is unassignable` error

Recently delving into TypeScript, I've encountered an issue within my project that was created using create-react-app with TypeScript and incorporates JSS. It appears that certain CSS properties are causing errors. Specifically, the pointerEvents and ...

What is the best approach in Typescript to ensure type understanding when importing using require()?

Currently, I am working with TypeScript within IntelliJ. Let's say I have the following code: const functions = require('firebase-functions'); Then I proceed to use it in this manner: exports.doSomething = functions.https.onCall((data, c ...

What is the correct way to construct an object in TypeScript while still taking types into account?

Hey, I'm having trouble implementing a common JavaScript pattern in TypeScript without resorting to using any to ignore the types. My goal is to write a function that constructs an object based on certain conditions and returns the correct type. Here& ...

When a list item is clicked, the 'active' class is added to it and removed from its sibling elements in Angular 8

By default, the first list item will be active. When you click on any list item, it should add a class of 'active' and remove the class from its siblings. public items = [{ value: 'All', }, { value: 'Photos', ...

Using TypeScript with Angular-UI Modals

Currently, my goal is to create a modal using angular-ui-bootstrap combined with typescript. To begin, I referenced an example from this link (which originally utilizes jQuery) and proceeded to convert the jQuery code into typescript classes. After succes ...

A Typescript interface featuring a method named 'create'

Currently, I am facing a challenge in creating a TypeScript definition for an external library that features a factory function named "new". The issue arises when attempting to add a function named "new" within the interface as it conflicts with the constr ...

Newest preact and typescript packages causing issues with type validation

Despite my efforts to integrate preact with TypeScript, I have encountered a problem where incorrect types can be passed without any error being raised. I am in the process of transitioning our codebase from plain JavaScript to preact with type scripting. ...

How to generate a new array in Angular by combining elements from two existing arrays for common items

I am currently working on a TypeScript function to compare two arrays and generate a third array containing the common items. For example: employees: any; offices: any; constructor() { this.employees = [ { fname: "John", lname: "James", sta ...

Issue - Unrecognized listen EADDRINUSE :::5432 detected in Windows Command Prompt

I encountered an issue when I tried running gulp serve --nobrowser, resulting in the following error: { Error: listen EADDRINUSE :::5432 at Object._errnoException (util.js:992:11) at _exceptionWithHostPort (util.js:1014:20) at Server.setupListenHandle [as ...

Error encountered in Ngrx data service when using Angular resolver

I have successfully implemented an NGRX Data entity service and now I'm looking to preload data before accessing a route by using a resolver. import { Injectable } from "@angular/core"; import { ActivatedRouteSnapshot, Resolve, RouterS ...

Listening for keypress events on a div element using React

I'm currently struggling with implementing a keypress listener on a component. My goal is to have my listener activated whenever the "ESC" key is pressed, but I can't seem to figure it out. The function component I am working with is quite stra ...

What is the most effective way to eliminate all values in an object key array except for one specific value?

Currently, I am developing an angular project and have encountered an object with the following structure: const obj = { fruits: ['apple', 'orange', 'None'], nation: ['usa'], city: ['New York', ' ...