Ways to set a default value for a function that returns an unknown type in TypeScript

In my code, I have a customizedHook that returns a value of type typeXYZ || unknown. However, when I try to destructure the returned value, I encounter an error

TS2339: Property 'xyz' does not exist on type 'unknown'
, even though the data actually returns as xyz: {} and abc: ['string1', 'string2']. How can I resolve this issue?

export function useAPICall(): typeXYZ || unknown {
  const {data} = useQuery(['apiCallData'], async () => {
    const value: typeABC = (await cbFunction()) as typeABC;
    return value?.defaultValue;
  });

  return {data};
//console.log(data)
//{xyz: {abc: 'asdasda', cde: 'xzczxc'}, abc: ['aaaa','bbbb','cccc']}
}

const {xyz: {}, abc: string[]} = useAPICall()

Answer №1

Using a union type like TypeXYZ | unknown (with a single pipe) actually makes the type restrictions stricter than those of the individual types in the union, which may not be what you expect.

For instance, consider the following code snippet:

const a = get_value() as number | string;
const b = parseInt(a, 10);

An error will occur here because parseInt does not accept arguments of type number. This means that any code involving the union type must be valid for all types within it. Since unknown is the most restrictive type and usually requires casting to be used, it essentially overrides XYZ completely.

On the other hand, if you were to use any, the least restrictive type, there would be little point in having TypeXYZ at all since any allows unrestricted manipulation of the object.

If you are destructuring an object xyz, you should ideally confirm beforehand that the object is indeed of type TypeXYZ and then cast it using as TypeXYZ.

It's important to remember that Typescript has no knowledge of your runtime types, so if an API returns unexpected data, Typescript cannot assist you with that. In such cases where the API response may vary, some form of runtime type-checking is necessary, like the example below:

const res = useApiCall();
if (res.xyz) {
  const { xyz } = res as TypeXYZ;
}

Answer №2

If you want to assign default values to an unspecified type, you can achieve it through the following method:

const defaults: { xyz: string, pqr: number} = { xyz: "defaultvalue", pqr: 456 }
const someUnknownType: unknown = { xyz: "xyz123" }

const finalResult: { xyz: string, pqr: number} = { ...defaults, ...someUnknownType }
// finalResult will be { xyz: "xyz123", pqr: 456 }

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

Develop a novel object framework by merging correlated data with identical keys

I am trying to organize the related data IOrderData by grouping them based on the productId and brandId. This will help create a new array of objects called IOrderTypeData, where the only difference between the objects is the delivery type. Each product id ...

What is the best way to load a component every time the function is called?

Currently, I am utilizing Angular and endeavoring to create reusable actions such as bulk updates, deletes, and deactivations. I have incorporated all of these actions into another component and aim to use it as a generic method. This implies that I have ...

What could be causing the issue of CSS Styles not being applied to an Angular 2 component with Vaadin elements?

Currently, I am immersed in the tutorial on Vaadin elements using Angular 2 that I stumbled upon here In section 5.3, Styles are applied to the app.component.ts as shown below import { Component } from [email protected]/core'; @Component({ select ...

There is no way to convert a strongly typed object into an observable object using MobX

I have been utilizing the MobX library in conjunction with ReactJS, and it has integrated quite smoothly. Currently, I am working with an observable array structured as follows: @observable items = []; When I add an object in the following manner, everyt ...

Component coding in Angular 2 allows for seamless integration and customization of Material

I am looking to initiate the start.toggle() function (associated with Angular 2 material md-sidenav-layout component) when the test() method is triggered. How can I execute md-sidenav-layout's start.toggle() in the app.component.ts file? app.componen ...

The compatibility issue arises when using Material UI Portal with TypeScript, specifically with the 'children' property types

When rendering a component using Material-UI Portal that includes several Material UI buttons, the following code is used: <Portal container={this.myContainer}> <Button onClick={this.handleClick}>Do something</Button> //other but ...

Developing a user interface that filters out a specific key while allowing all other variable keys to be of the identical type

As I dive deeper into the TypeScript type system, I find myself grappling with an interface design query. Can anyone lend a hand? My goal is to craft an interface in TypeScript where certain object keys are of a generic type and all other keys should be o ...

Error: The npm-link library encountered an invalid hook call

Problem Description: I am working on developing a package named eformless. To set up the package, I utilized CRA to create a directory named sandbox where I linked the package. However, I keep encountering an error when attempting to launch the sand ...

Error encountered in Angular 7.2.0: Attempting to assign a value of type 'string' to a variable of type 'RunGuardsAndResolvers' is not allowed

Encountering an issue with Angular compiler-cli v.7.2.0: Error message: Types of property 'runGuardsAndResolvers' are incompatible. Type 'string' is not assignable to type 'RunGuardsAndResolvers' This error occurs when try ...

Reactive forms in Angular now support changing focus when the Enter key is pressed

I have successfully created a table and a button that generates dynamic rows with inputs inside the table. One issue I'm facing is that when I press enter in the first input, a new row is created (which works), but I can't seem to focus on the ne ...

The function type '(state: State, action: AuthActionsUnion) => State' cannot be assigned to the argument

I have encountered a persistent error in my main.module.ts. The code snippet triggering the error is as follows: @NgModule({ declarations: [ PressComponent, LegalComponent, InviteComponent ], providers: [ AuthService ], imports: ...

What is the best method to create a TypeScript dictionary from an object using a keyboard?

One approach I frequently use involves treating objects as dictionaries. For example: type Foo = { a: string } type MyDictionary = { [key: string]: Foo } function foo(dict: MyDictionary) { // Requirement 1: The values should be of type Foo[] const va ...

The upcoming construction of 'pages/404' page will not permit the use of getInitialProps or getServerSideProps, however, these methods are not already implemented in my code

Despite my efforts to search for a solution, I have not found anyone facing the same issue as me. When I execute next build, an error occurs stating that I cannot use getInitalProps/getServerSideProps, even though these methods are not used in my 404.tsx f ...

Is there a method to automatically eliminate all unnecessary properties in an Angular project?

In my extensive Angular project, I suspect that there are numerous declared properties in .component.ts that are not being used. Is there a method available to automatically eliminate all unused properties within an Angular project while also taking into ...

What causes images to unexpectedly expand to fill the entire screen upon switching routes in Next.js?

I'm in the process of creating a website using Next and Typescript, with some interesting packages incorporated: Framer-motion for smooth page transitions Gsap for easy animations One issue I encountered was when setting images like this: <Link&g ...

Issues arise when Typescript fails to convert an image URL into a base64 encoded string

My current challenge involves converting an image to base 64 format using its URL. This is the method I am currently using: convertToBase64(img) { var canvas = document.createElement("canvas"); canvas.width = img.width; canvas.height = img.he ...

Is there a way for me to loop through an object without prior knowledge of its keys?

Upon receiving data from the server, it looks something like this: { "2021-10-13": { "1. open": "141.2350", "2. high": "141.4000", "3. low": "139.2000", "4. close& ...

In an Electron-React-Typescript-Webpack application, it is important to note that the target is not a DOM

Rendering seems to be working fine for the mainWindow. webpack.config.js : var renderer_config = { mode: isEnvProduction ? 'production' : 'development', entry: { app: './src/app/index.tsx', //app_A: './src/a ...

There is no universal best common type that can cover all return expressions

While implementing Collection2 in my angular2-meteor project, I noticed that the code snippets from the demo on GitHub always result in a warning message being displayed in the terminal: "No best common type exists among return expressions." Is there a ...

Tips for passing TouchableOpacity props to parent component in React Native

I created a child component with a TouchableOpacity element, and I am trying to pass props like disabled to the parent component. Child component code: import React from 'react'; import {TouchableOpacity, TouchableOpacityProps} from 'react- ...