The 'XXX' property is not found in 'YYY' type but is necessary in 'ZZZ' type

I'm struggling with setting up class properties in TypeScript. Here is the TypeScript code that I am working on:

export class myClass  {
  a: number;
  b: number;
  public getCopy(anotherClass: myClass): myClass {
    return {
      a: anotherClass.a,
      b: anotherClass.b
    };
  }
}

However, I encountered this error message:

Property 'getCopy' is missing in type '{ a: number; b: number; }' but required in type 'myClass'

Why is it interpreting getCopy() as a property? Coming from a C# background, I am used to not having to initialize functions. Is there a way in TypeScript to instantiate a class and set properties without initializing functions like C# does? I would prefer something simpler like the C# code snippet below:

var newInstance = new myClass()
{
  a = 1,
  b = 2
};

Instead of resorting to this approach:

var newInstance = new myClass();
newInstance.a = 1;
newInstance.b = 2;

Is achieving this elegance possible in TypeScript?

Answer β„–1

To start fresh, initiate a duplicate instance of the myClass class:

public createDuplicate(newInstance: myClass): myClass {    
  return Object.assign(new myClass(), {...});
}

Answer β„–2

getCopy is a property of myClass. You are defining it as part of the myClass properties. To create an instance of myClass, you can also use Object notation:

const myClassInstance = {
  a,
  b,
  getCopy,
}

Since getCopy is a required property in myClass, it must be included and its type must match the declaration in myClass, which means it should be a function.


However, it may not be necessary to have an instance method that generates a copy of the class. Instead, you could make this functionality a standalone function. Additionally, copying the top level of an object can be achieved in multiple ways such as using the spread operator, eliminating the need for a custom function.

const myClass = new myClass();
myClass.a = 1
myClass.b = 2;
const myClassCopy = { ...myClass };

Answer β„–3

Instead of creating a class for the provided code, you can simply define your data structure using an interface.

interface DataStructure {
  a: number;
  b: string;
}

After defining the interface, you can create an object with these properties like this:

const instance: DataStructure = { a: 5, b: 'test' };

You can utilize the interface as parameters in your functions or return values without needing a class. For example:

function someFunction( data: DataStructure): void {
}

someFunction(instance); // works
someFunction({a: 10, b: 'example'}); // works
someFunction({a: 10}); // will not work as 'b' is required

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

Discovering the parameter unions in Typescript has revolutionized the way

My current interface features overloaded functions in a specific format: export interface IEvents { method(): boolean; on(name: 'eventName1', listener: (obj: SomeType) => void): void; on(name: 'eventName2', listener: (obj: Som ...

Querying with Node SQLite fails to return a value

So, here's my little dilemma: I have 3 methods that need to access a database file (SQLite3). export function F_SetupDatabase(_logger: any): void export function Q_RunQuery(query: string, db: "session" | "global"): any export func ...

Using Datatable.net with Angular 6 for Change Monitoring

I've been encountering several issues with the custom datatable component that I created. One specific problem is that when I delete a row from my datatable, not only does the row disappear, but also the pagination functionality and other features st ...

The console is displaying a promise that is pending, rather than the desired data

Here is the content of my file: 'use strict' import * as moment from "moment"; import { Report} from "./Report"; import { Timeframe} from "./Timeframe"; import { ReportComparison } from "./ReportComparison"; function test(firstFrom: string, fi ...

Elements are unresponsive to scrolling inputs

My Ionic 2 input elements are not scrolling to the top when the keyboard is shown. I've tried everything I could find on Google, making sure the keyboard disable scroll is set to false. However, I still can't figure out what's causing the sc ...

Looking to categorize and sum the values within an array of objects using JavaScript?

I'm looking to optimize this response data within my Angular application. res=[ { "url": "/page1", "views": 2 }, { "url": "/page2", "views": 1 }, { "url": "/page1", "views": 10 }, { "url": "/page2", "views": 4 }, { "url": "/page3", "views": 1 }, ...

It’s not possible for Typescript to reach an exported function in a different module

Having trouble referencing and using exported methods from another module. I keep getting an error that says 'There is no exported member in SecondModule'. module FirstModule{ export class someClass{ constructor(method: SecondModule ...

What is the best way to define a named, optional parameter in TypeScript-React that can accept an object with optional fields and default values?

Is there a way to achieve something similar to the style property found in default HTML components? For instance: <div ref={ref} style={{ overflow: 'visible', height: 600, width: '100%' }}> The style prop is optional, and the fie ...

An issue has arisen regarding the type definition for the random-string module

I am currently working on creating a .d.ts file for random-string. Here is the code I have so far: declare module "random-string" { export function randomString(opts?: Object): string; } When I try to import the module using: import randomString = ...

Get every possible combination of a specified length without any repeated elements

Here is the input I am working with: interface Option{ name:string travelMode:string } const options:Option[] = [ { name:"john", travelMode:"bus" }, { name:"john", travelMode:"car" }, { name:"kevin", travelMode:"bus" ...

Guide on Reacting to an Occurrence in Angular

I have a scenario where an event is triggered every 10 seconds. After subscribing to the event on the receiving end, I need to figure out how to send data back to the class responsible for emitting the event. constructor(@Inject(ABC.XYZ) private events: ...

Debugging Typescript code with line numbers

When opening the console in a browser, typically the javascript line number of a function call or error message is displayed. However, my current setup involves using TypeScript, which gets compiled to Javascript. I am wondering if there is a way to retr ...

Transmit data from a child component to a Vue JS page through props, and trigger the @blur/@focus function to access the prop from the parent component

Seeking guidance on working with props in Vue JS. As a newcomer to Vue, I hope that my question is clear. I've included my code snippet below, but it isn't functioning correctly due to missing Vue files. In my attempt to use a prop created in t ...

What is the correct way to convert a base type value to its extended type in TypeScript?

Consider the TypeScript code block below: type URLEx = URL & { custom: string; }; const url = new URL("http://localhost:3000/foo/var"); const url_x: URLEx = { ...url, custom: "hello", }; console.log(url); // Output properti ...

Developing a React-based UI library that combines both client-side and server-side components: A step-by-step

I'm working on developing a library that will export both server components and client components. The goal is to have it compatible with the Next.js app router, but I've run into a problem. It seems like when I build the library, the client comp ...

Angular Project: Exploring Classes and Interfaces with and without the Export Keyword

Currently, I am delving into the world of Angular. I have taken up a video course and also referred to a PDF book, but I find myself perplexed when it comes to understanding the usage of the "export" keyword... The PDF course focuses on Angular 5 and util ...

Exploring the Capabilities of TypeScript 1.8 in Visual Studio 2017

Recently, I've encountered an issue with my Visual Studio project that was created using TypeScript 1.8 in Visual Studio 2015. Upon upgrading to Visual Studio 2017 and attempting to open the project in the new IDE, I noticed that the TypeScript versio ...

The reason behind the clickable issue with my duplicate <ion-select>

I've been working on a form using HTML, CSS, and JavaScript where I implemented an "Add" button to duplicate the form. The issue arises with the ion-select element within the duplicated form. While the original form displays all predefined options upo ...

An issue occurred while attempting to retrieve Firebase data using an HTTP GET request

When trying to retrieve my data from firestore using an HTTP get request, I encountered an error. It might be helpful if my data in firestore was stored in JSON format. I'm not sure if this is feasible. <!DOCTYPE html> <html lang="en"> ...

The file parameter in the upload is consistently undefined in tsoa-swagger

Having trouble with Tsoa nodejs File upload Followed the tsoa documentation for writing the method, but the output variable is consistently undefined This is my current method https://i.sstatic.net/YrNc0.png @Post('/uploadNewExporterTemplate&apos ...