Give back the default value of a generic parameter

Switching from C# to Typescript, I am trying to figure out how to return the default value of a generic parameter. In C#, we can achieve this with a simple function like so:

private T TwiceAsMuch<T>(T number)
{
  if (number is int n)
    return (T)(object)(n * 2);
  else if (number is float f)
    return (T)(object)(f * 2);
  else
    return default;
}

But how do I accomplish the equivalent of return default in Typescript?

Context

I am working on a wrapper function that makes use of axios.post and should return the response in the specified type:

private static async postInternal<T>(route: string, data: unknown): Promise<T> {
  await Vue.$axios.get('/sanctum/csrf-cookie')
  const res = await Vue.$axios.post<T>(`${route}`, data)
    .then(res => res.data)
    .catch(err => {
      openErr(err)
      return ???
    })
}

What should replace ??? in this code snippet?

Answer №1

Unfortunately, there is no direct equivalent in this scenario. A value is associated with a type, but a type itself may not have a default value.

Although I am not familiar with C#, as mentioned in this response, using the return default statement behaves in the following manner:

The default keyword will return null for reference types and zero for numeric value types.

This concept does not apply to Typescript. Unlike C#, Typescript compiles to Javascript which lacks static typing. Consequently, during runtime, the type of T becomes indistinguishable within the executing code base.

In Typescript, the following examples:

postInternal<number>('/path', { data: true })

And:

postInternal<{ a: { b: { c: number } } }>('/path', { data: true })

Both ultimately compile down to the same javascript output:

postInternal('/path', { data: true })

Thus, determining the type of T at runtime is unfeasible. Consequently, basing your code's path solely on the type of T is impossible.


One common approach to handling this situation is by allowing the result to be nullable and returning null in case of an error:

private static async postInternal<T>(route: string, data: unknown): Promise<T | null> {
  //...
}

const num = postInternal<number>('/path', { data: true }) ?? 0

Alternatively, you can throw an error and have the caller catch it and decide how to proceed:

try {
  const num = postInternal<number>('/path', { data: true })
} catch (error) {
  console.error('Oops! Something went wrong.', error)
}

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

JavaScript Generated From TypeScript Encountering TypeError

Why is the JavaScript code produced by this TypeScript snippet causing a TypeError upon execution? class Foo { public foo: { bar: number }; constructor() { this.foo["bar"] = 123; } } new Foo(); Even though I'm compiling it with the ...

Are undefined Static Properties an Issue in Mocked Classes? (Jest)

Currently, I am facing a challenge in mocking a class that includes a static property. jest.mock("../../src/logger/index"); import { Logger } from "../../src/logger/index"; // .. const LoggerMock = Logger as jest.MockedClass<typeof ...

Refresh Angular 2 data after a related data update

I am facing an issue with my <select> elements in Angular. One for the Districts and another for the Cities. The districts are fetched using the getDistricts() function within the ngOnInit() function without any problems. However, I am unsure how to ...

Arrow functions serve as references to variables within a specific context

Is there a way to pass an arrow function as a variable in a tab? I am working with a function that looks like this: public handleLogin(data) { this.socket.send(data); [...] } This function is located within a functions tab: let tab = [this.handleLo ...

What is the method for defining the POST response body in Bun and Elysia?

My goal is to modify the response body of a POST route in Elysia, but after analyzing CTX, it seems that only the request is available and I am unable to locate any information on how to alter the response. Specifically, I aim to assign a task ID to users ...

Limit function parameters to only accept values with matching keys

I am relatively new to using TypeScript and am currently working on a project that involves handling various shapes of data from different sources. My goal is to pass this data to different aggregator classes, with one aggregator class corresponding to eac ...

Tips for updating an Angular renderer's value

I have a challenge with implementing a background color change when clicking on a th element. Currently, it works fine when I click on it, but I would like to make it so that if I click on another th element, the previous one will turn off. However, if I ...

What is the best way to shift focus to the next input field once the character limit has been reached, especially when the input is contained

My challenge lies in having six input fields arranged side by side in a single row: In my component.html file: onDigitInput(event: any) { let element; if (event.code !== 'Backspace') element = event.srcElement.nextElementSibling; consol ...

Make sure to wait for the observable to provide a value before proceeding with any operations involving the variable

Issue with handling observables: someObservable$.subscribe(response => this.ref = response); if (this.ref) { // do something with this.ref value } ERROR: this.ref is undefined How can I ensure that the code relying on this.ref only runs after ...

How can RootStateOrAny be turned off in React with typescript?

Whenever I need to employ useSelector, I find myself repeating this pattern: const isLoading = useSelector( (state) => state.utils.isLoading ); Is there a shortcut to avoid typing out RootStateOrAny each time? It's starting to become a hassl ...

Struggling to reach the same level of bundle optimization with webpack + angular when compared to angular-cli

I am currently facing an issue with two Angular projects that I have. One is developed using angular-cli, while the other one is built with Webpack and utilizes @ngtools/webpack. Both projects are based on Angular 7.1.4 and @angular-devkit 0.13.5. The code ...

Issue with AWS SDK client-S3 upload: Chrome freezes after reaching 8 GB upload limit

Whenever I try to upload a 17 GB file from my browser, Chrome crashes after reaching 8 GB due to memory exhaustion. import { PutObjectCommandInput, S3Client } from '@aws-sdk/client-s3'; import { Progress, Upload } from "@aws-sdk/lib-storage& ...

Navigating to view component in Angular2 Routing: Issue with router-link click event not working

I have set up my app.routes.ts file and imported all the necessary dependencies. Afterward, I connected all the routes to their respective Components as follows: import {ModuleWithProviders} from '@angular/core'; import {Routes, RouterModule} f ...

Issue with Angular 4 Routing: Links are opening in new window instead of within router-outlet

I am currently facing an issue while trying to display the SuburbDataComponent HTML on the DASHBOARD-SIDE-PANEL-COMPONENT.HTML. When I click on Dashboard, it opens a new window but only displays the SuburbDataComponent.html without showing the side panel ...

Express: custom middleware specific to the project that enhances the Express.Request object

Currently, I am in the process of developing a node server using Express and TypeScript 1.7. The middleware I am working with is tailored to my project and extends the existing express Request or Response interface. However, I am encountering issues as Typ ...

Incorrect order in Angular2 NgFor within tree model when elements are removed and then added back

Currently experimenting with Angular 2 alpha version 44. Working with a tree model that utilizes recursion for display purposes. Each group contains 'Criterions', 'Segments', and other 'Groups'. Elements can be added or delet ...

Guide to updating all object values in Typescript

I am working with an object that looks like this: enum FeatureNames = { featureA = 'featureA', featureB = 'featureB', featureC = 'featureC' } interface FeatureDetails { on: boolean; } type Features = Record<Featu ...

The error code TS2322 indicates that the type 'string | null' cannot be assigned to the type 'number'

I am completely new to both Angular and TypeScript, so I'd like to start by mentioning that. In my Angular program, I have implemented routing to display more information on a separate page. The errors are occurring within the ngOnInit() method: Th ...

React TS implementation of radial animated focus effect using mask-image technique

I am attempting to replicate the Radial animated focus effect using mask-image: Codepen. While I could simply copy and paste the CSS into a .css file, I want to achieve the same outcome with a styled component. I have defined the CSS within my styled compo ...

Tips for extracting IDs from multiple checkboxes that have been selected upon submission in an Ionic 2+/Angular 2+ environment

I am facing an issue with retrieving the ID of the checked item upon submission. While I can successfully fetch the selected ID on change, I am unable to do so on submit. It is worth noting that the data I am receiving does not include a "checked" value. T ...