What is the best way to overload a function based on the shape of the argument object in

If I am looking to verify the length of a string in two different ways (either fixed or within a specific range), I can do so using the following examples:

/* Fixed check */
check('abc', {length: 1}); // false
check('abc', {length: 3}); // true

/* Range check */
check('xyz', {minLength: 5, maxLength: 10}); // false
check('xyz', {minLength: 1, maxLength: 10}); // true
check('xyz', {minLength: 3, maxLength: 3}); // true

To achieve this, I have defined two interfaces initially:

interface StringFixed {
  length: number;
}

interface StringRange {
  minLength: number;
  maxLength: number;
}

Next step is to create the function implementation:

function check(value: string, schema: StringFixed): boolean;
function check(value: string, schema: StringRange): boolean;
function check(value: string, schema: StringFixed | StringRange): boolean {
  if (typeof schema.length !== 'undefined') { // ERROR
    // Implementing fixed length check logic
  } else {
    // Implementing range check logic
  }
}

However, TypeScript raises an error at runtime on the line with 'length' property access:

TS2339: Property 'length' does not exist on type 'StringFix | StringRange'

How can I rectify this issue and successfully execute this code in TypeScript?

Answer №1

Almost there! :-) You're inquiring about the type of a property value that is expected to exist (typeof schema.length). To create a type guard, you should check for the existence of the property like this:

if ("length" in schema) {
    // Correct check
} else {
    // Range check
}

Here is a playground link to see it in action on TypeScript 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

Testing NextJS App Router API routes with Jest: A comprehensive guide

Looking to test a basic API route: File ./src/app/api/name import { NextResponse } from 'next/server'; export async function GET() { const name = process.env.NAME; return NextResponse.json({ name, }); } Attempting to test ...

Interact with SOAP web service using an Angular application

I have experience consuming Restful services in my Angular applications, but recently a client provided me with a different type of web service at this URL: http://123.618.196.10/WCFTicket/Service1.svc?wsdl. Can I integrate this into an Angular app? I am ...

Enhancing a Given Interface with TypeScript Generics

I am looking to implement generics in an Angular service so that users can input an array of any interface/class/type they desire, with the stipulation that the type must extend an interface provided by the service. It may sound complex, but here's a ...

Adjusting the Material UI Select handleChange function

const handleObjectChange = (event: React.ChangeEvent<{ value: unknown }>) => { const { options } = event.target as HTMLSelectElement; const selectedValues: object[] = []; for (let i = 0, l = options.length; i < l; i += 1) { if ...

node-ts displays an error message stating, "Unable to locate the name '__DEV__' (TS2304)."

I recently inserted __DEBUG__ into a TypeScript file within my NodeJS project. Interestingly, in VSCode, no error is displayed. However, upon running the project, I encounter an immediate error: error TS2304: Cannot find name '__DEBUG__'. I att ...

Every time I make updates, I have to reload the page to see the changes take effect

Currently, I am in the process of developing a web application that utilizes Firebase Firestore as the backend and NoSQL database, with Angular serving as the frontend. With frequent updates and changes being made to the website, it becomes cumbersome to c ...

Ionic 3: Struggling to Access Promise Value Outside Function

I've encountered an issue where I am unable to retrieve the value of a promise outside of my function. It keeps returning undefined. Here's what I have attempted so far: Home.ts class Home{ dd:any; constructor(public dbHelpr:DbHelperProvider ...

Filtering input for multiple header columns in an Angular table

A complex Angular table structure has been implemented with three columns. Each column header contains an input field for Stock Number, Case, and Availability. Users have the flexibility to search using a Single Input (Stock Number OR Case OR Availability ...

Changing a d3 event from JavaScript to Typescript in an Angular2 environment

I am a beginner in Typescript and Angular 2. My goal is to create an Angular2 component that incorporates a d3js tool click here. However, I am facing challenges when it comes to converting it to Typescript. For instance, I am unsure if this code rewrite ...

Trouble with invoking a function within a function in Ionic2/Angular2

Currently, I am using the Cordova Facebook Plugin to retrieve user information such as name and email, which is functioning correctly. My next step is to insert this data into my own database. Testing the code for posting to the database by creating a func ...

Assembly of these elements

When dealing with a structure where each property is of type These<E, A> where E and A are unique for each property. declare const someStruct: { a1: TH.These<E1, A1>; a2: TH.These<E2, A2>; a3: TH.These<E3, A3>; } I inte ...

Typescript may fall short in ensuring type safety for a basic reducer

I have been working on a simple reducer that uses an object to accumulate values, aiming to maximize TS inference. However, I am facing difficulties in achieving proper type safety with TypeScript. The issue arises when the empty object does not contain an ...

invoking a function at a designated interval

I am currently working on a mobile application built with Ionic and TypeScript. My goal is to continuously update the user's location every 10 minutes. My approach involves calling a function at regular intervals, like this: function updateUserLocat ...

Is it possible to trigger an ajax function two times using the onchange event?

Here is my custom ajax function: var customRequestObject = false; if(window.XMLHttpRequest){ customRequestObject = new XMLHttpRequest(); } else if (window.ActiveXObject){ customRequestObject = new ActiveXObject("Microsoft.XMLHTTP"); } function f ...

Is there a way to define an object's keys as static types while allowing the values to be dynamically determined?

I am attempting to construct an object where the keys are derived from a string union type and the values are functions. The challenge lies in wanting the function typings to be determined dynamically from each function's implementation instead of bei ...

Bidirectional communication linking an Angular 2 component and service utilizing the power of Observables

I'm having difficulties establishing a simple connection between an Angular 2 component and service using Observable. I've been trying to achieve this, but I can't seem to get it right. Here's the scenario: My component HeroViewerCompo ...

Encountering an error when trying to access this.$store.state in a basic Vuex

Encountered an error with return this.$store.state.counter: The property '$store' does not exist on the type 'CreateComponentPublicInstance<{}, {}, {}, { counter(): any; }, {}, ComponentOptionsMixin, ComponentOptionsMixin, EmitsOptions, ...

Setting up systemjs.config.js for utilizing relative paths within IIS - A step-by-step guide

My new ASP.NET MVC web application utilizes Angular for its UI components. I have set up the necessary config files in my project (e.g. package.json and systemjs.config.js). Created a test page Index.cshtml to test out the template in app.component.ts. The ...

Tips for generating a subject in rx.js while utilizing 2 parameters

Within my Angular2 application, I am utilizing a communication service to handle interactions between components. When calling the method: this.notification.create('test'); The service structure is as follows: export class NotificationServic ...

Utilizing TypeScript to Retrieve the Parameter Types of a Method within a Composition Class

Greetings to the TS community! Let's delve into a fascinating problem. Envision having a composition interface structured like this: type IWorker = { serviceTask: IServiceTask, serviceSomethingElse: IServiceColorPicker } type IServiceTask = { ...