Can a type be created that resolves to either of two specific types?

If I have multiple functions that return either a number or a date, is there a way to define a type that encompasses both?

For example, instead of:

foo1(): number | Date {}
foo2(): number | Date {}

Can we do something like this:

foo1(): NumberOrDate {}
foo2(): NumberOrDate {}

Is there a better approach to avoid repeating 'number | Date' and stay DRY?

Answer №1

If you want to use a union type, you can simply create a type alias:

type NumberOrDate = number | Date

function example1(): NumberOrDate { return 1;}
function example2(): NumberOrDate { return new Date}

Check it out on the Playground

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

Troubles arise when compiling TypeScript to JavaScript

I have been experimenting with TypeScript, specifically for working with classes. However, I am facing an issue after compiling my TS file into JS. Below is the TypeScript code for my class (PartenaireTSModel.ts): export namespace Partenaires { export ...

Typescript's Confusion with Array Types: Understanding Conditional Types

Here is the setup I have. The concept is to receive a generic and options shape, deduce the necessary options based on the generic and the type key of the options shape, and appropriately restrict the options. type OptionProp<T extends string | boolean& ...

For editing values that have been dynamically inserted

In my JSON data, there is a variable named address that contains multiple objects (i.e., multiple addresses). I am displaying these multiple addresses as shown in the following image: https://i.sstatic.net/1AG34.png When clicking on a specific address ( ...

Managing form input in Ionic2 components from external sources in Angular2

Hello there, I am currently facing an issue with managing form validation along with proper styling for nested forms. Here's what I'm aiming to achieve: I have a Page that displays Tabs components with four tabs. Each tab represents a separate @ ...

What is the correct way to handle the return value of an useAsyncData function in Nuxt 3?

How can I display the retrieved 'data' from a useAsyncData function that fetches information from a pinia store? <script setup lang="ts"> import { useSale } from "~/stores/sale"; const saleStore = useSale(); const { da ...

Sidenav selector unable to display Angular component

I'm facing a dilemma. I have the following code in my app.component.html file: <mat-sidenav-container class="sidenav-container"> <app-sidenav></app-sidenav> <mat-sidenav-content> <app-header></app-header> ...

Is there a way to create identical copies of data with the identical names?

Here is the code I have written: this.temp1.push(this.json); for(let i=0; i<this.temp1.length; i++){ if(this.temp1[i].name == this.json.name){ this.orderList[i] = this.json; this.DBorder[i] = this.order_json; } ...

Angular 2 signal sender

I have a specific class definition for my Project: export class Project { $key: string; file: File; name: string; title: string; cat: string; url: string; progress: number; createdAt: Date = new Date(); constructor(file: File) { th ...

Does an AsyncMethod().Result equivalent exist in typescript?

When working in C#, you have the ability to call the result of an asynchronous method synchronously by accessing the Result property. For example: var returnVal = AsyncMethod().Result; What is a similar approach in typescript? ...

Encountering an issue with Angular 12 where a TypeError is being thrown, specifically stating "Cannot read properties of null (reading 'length') at

I encountered an error message while making a http request in my Angular Service. Strangely, this error only occurs after I logout, but it disappears upon logging back in: Below is the code snippet of my authentication Service: import { Injectable } from ...

What steps can be taken to ensure that typescript exports remain backward compatible with module.exports?

I initially defined a node.js module in the following way: function sayHello(){ // do something } module.exports = sayHello; After transitioning to typescript, I created sayHello.ts like this: function sayHello():void { // do something } export de ...

Can we utilize the elements in Array<keyof T> as keys in T?

Hello, I am trying to develop a function that accepts two parameters: an array of objects "T[]" and an array of fields of type T. However, I am encountering an issue when I reach the line where I invoke el[col] Argument of type 'T[keyof T]' i ...

Bringing Typescript functions into the current module's scope

Is it possible to import and reference a module (a collection of functions) in typescript without the need for the Module. prefix? For instance: import * as Operations from './Operations'; Can I access Operations.example() simply as example()? ...

Create duplicates of both the array and its individual elements by value

I'm having trouble figuring out how to properly copy an array along with all its elements. In my model, I have a name and options, both of which are strings. This is what I currently have: const myArrayToDuplicate = [myModel, myModel, myModel] My ...

What is the most effective way to perform unit testing on the "present" function of an Ionic alert controller?

I decided to write a unit test for the alert present function that gets triggered after creating an alert. This is what my code looks like. it('should call attempt To call alert present', async () => { const alert = { header: 'P ...

Step-by-step guide on implementing Form.create in TypeScript and Ant Design with function components

Having trouble compiling my form created using Form.create(). The error message I'm getting is: Argument of type 'FunctionComponent<MyProps>' is not assignable to parameter of type 'ComponentType<{}>'. Type 'Fu ...

Remove the export statement after transpiling TypeScript to JavaScript

I am new to using TypeScript. I have a project with Knockout TS, and after compiling it (using the Intellij plugin to automatically compile ts to js), this is my sample.ts file: import * as ko from "knockout"; ko; class HelloViewModel { language: Kn ...

Differences between tsconfig's `outDir` and esbuild's `outdir`Explanation of the variance in

Is there a distinction between tsconfig's outDir and esbuild's outdir? Both appear to accomplish the same task. Given that esbuild can detect the tsconfig, which option is recommended for use? This query pertains to a TypeScript library intended ...

The battle of Any, Generic Type, and Unknown in Typescript

Is it advisable to replace the type any with Generic Types? I understand that using type any is generally discouraged as it removes type checking in TypeScript, making it unsafe. So what is a better alternative - using unknown or generic types? For examp ...

Do parallel awaits in JS/TS work only on Chrome browsers exclusively?

Encountering a strange issue with promise resolution behavior in JS/TS. Using Node LTS. It seems that the difference lies in whether the promise resolves to a value that is later read in the code or if it's simply fire-and-forget (void response type). ...