Error caused by properties of a variable derived from an interface in the compiler

I'm confused as to why the compiler is saying that the properties "name" and "surname" don't exist on type "ITest1" within function test1. It's a bit unclear to me:

interface ITest1{
    name: string;
    surname: string;
    age: number;
}

interface ITest2{
    city: string;
    nation: string;
    isEU: boolean;
}


//function test1<ITest1, ITest2>(a:ITest1|ITest2): ITest1|ITest2{
    function test1<ITest1, ITest2>(a:ITest1|ITest2): string{
   return (a as ITest1).name +
   (a as ITest1).surname;

}

let a : ITest1 = {
    name:"",
    surname:"",
    age:0
};
a.name="John";
a.surname="Taylor";
a.age=30;

console.log(test1(a));

Answer №1

To correct your function (the purpose of <ITest1, ITest2> is unclear), simply modify it to:

function test1(a: ITest1 | ITest2): string {
  return (a as ITest1).name + (a as ITest1).surname;
}

Expected Output:

$ tsc index.ts && node index
$ JohnTaylor

Note:

In order to distinguish between properties in ITest1 and ITest2, you can perform the following check:

function test1(a: ITest1 | ITest2 ): string {
  if ('name' in a) {
    // 'a' implements ITest1
    return `${a.name} ${a.surname}`;
  }
  // 'a' implements ITest2
  return `${a.city} ${a.nation}`;

  // Alternatively:
  // return 'name' in a ? `${a.name} ${a.surname}` : `${a.city} ${a.nation}`;
}

...

console.log(test1(a));
console.log(test1({city: "Foo", nation: "Bar", isEU: false}));

Outcome:

John Taylor
Foo Bar

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

Tips for ensuring an animation is triggered only after Angular has fully initialized

Within this demonstration, the use of the dashOffset property initiates the animation for the dash-offset. For instance, upon entering a new percentage in the input field, the animation is activated. The code responsible for updating the dashOffset state ...

The 'split' property is not found on the 'Int32Array' type

ERROR located in src/app/account/phone-login/phone-login.component.ts(288,53): error TS2339: Property 'split' is not a valid property for type 'string | Int32Array'. Property 'split' cannot be found on type 'Int32Array& ...

Is there a way to retrieve the value of an option passed by serverless CLI in serverless.ts file?

As I explored the serverless framework with serverless.ts for configuration, a certain question came to mind. When utilizing the serverless CLI, passing values can be done in the following way: serverless offline --stage prod In the serverless.yml file, ...

I often find myself frustrated while using Next.js because the console automatically clears itself, making it difficult for me

I am facing an issue with my form in the Next.js app. Here is how it is defined: <form onSubmit = { async() => await getCertificate(id) .then(resp => resp.json()) .then(data => console.log(data)) }> Whenever there is an erro ...

Issue encountered with UglifyJs - Unexpected token: title (Subject)

My attempt to deploy my initial Angular application is not going smoothly. The build process fails and the error message I'm encountering states: ERROR in vendor.809dd4effe018f6b3d20.bundle.js from UglifyJs Unexpected token: name (Subject) [vendo ...

Instructions for designing a Loading Indicator or Progress Bar within the App Directory of NextJS

Having built a substantial web application using NextJS 13, I initially utilized the Pages Router. However, as I neared completion of the website, I decided to make the switch to the App Directory. The primary motivation behind this migration was not just ...

Navigating Errors within Express Class Using Typescript

I encountered an issue while transforming my Express.js application into a Typescript class, specifically with error handling. Below is the content of my App.ts class file: import express from 'express'; import compression from 'compression& ...

Encountered a bun runtime error stating "Possibly require an `extends React.JSX.IntrinsicAttributes` constraint for this type parameter."

I have a good understanding of ReactJS, but this topic seems to be more advanced. I am working with generics in TypeScript and have the following code: export const withPopover = <T,>(WrappedComponent: React.ComponentType<T>) => { const ...

Error message: NextJs throws aReferenceError when trying to access the document object on page refresh

encountered the error ReferenceError: document is not defined when attempting to refresh the page I am working on creating a component using react-quill and then calling that component within a page. This is my component : import React, { useState } from ...

Remove the package from the @types folder within the node_modules directory

I currently have the 'mime' library in my node_modules directory and I am looking to completely remove it from my project, along with its @types files. The reason for this is that the old mime package is not functioning correctly for me, so I wan ...

Customizing Components in Angular 2/4 by Overriding Them from a Different Module

Currently, I am utilizing Angular 4.3 and TypeScript 2.2 for my project. My goal is to develop multiple websites by reusing the same codebase. Although most of the websites will have similar structures, some may require different logic or templates. My p ...

Aligning the React Navigation header component's bottom shadow/border width with the bottom tabs border-top width

Currently, I am working on achieving a uniform width for the top border of the React Navigation bottom tabs to match that of the top header. Despite my efforts, I am unable to achieve the exact width and I am uncertain whether it is due to the width or sha ...

Strategies for Handling Errors within Observable Subscriptions in Angular

While working with code from themes written in the latest Angular versions and doing research online, I've noticed that many developers neglect error handling when it comes to subscription. My question is: When is it necessary to handle errors in an ...

Phaser.js troubleshooting: Overcoming TypeScript errors

I encountered two persistent errors that I have been unable to resolve. While the application runs smoothly in Vite, it fails to transpile due to the mentioned errors outlined below: import Phaser from "phaser"; export default class GameScene ex ...

Ionic has been experiencing issues with inaccurate boolean results being generated by Angular typescript

I have created a random number generator that requires the user to input a maximum and minimum value to generate a random number within that range. The application will show an error under two conditions: If either of the numbers entered is negative If t ...

What is the most suitable data type to represent an empty object?

When I declared the return type of the function below as {}, eslint flagged an error stating not to use {} as a type because it actually means "any non-nullish value". After understanding the meaning behind this error, I realize that specifying return typ ...

Dealing with arrays in Typescript and flattening them using the RX

Struggling with a problem involving RXJS transformation in an Ionic 2 application. My goal is to flatten a JSON file into objects, here is the simplified JSON structure: [{ "language": "it", "labels": { "name": "Hi", }, "t ...

Listening for a long press in Angular 2: A step-by-step guide

Check out this link for an AngularJS example. Curious how this functionality translates to Angular 2? ...

Create a specific definition for a packaged item with limited access

As I worked with a package that lacked types, I took the initiative to create a type definition for it. The specific package in question is react-date-range. In order to accommodate this new type definition, I established a directory where it could be loca ...

In the production build, the RegEx validation is lacking and fails to accept certain characters like 0, 2, 7, a, c, u, x, and occasionally z

Incorporating Angular 15.2.10 and Typescript 4.9.5, the RegEx utilized in one of my libraries and exposed via a service is outlined as follows: private readonly _DISALLOWED_CHARS_REGEX_GENERAL = new RegExp(/^[^\\/\?\!\&\: ...