Reputation: 794
I'm having trouble initializing class properties. I have typescript code like this.
export class myClass {
a: number;
b: number;
public getCopy(anotherClass: myClass): myClass {
return {
a: anotherClass.a,
b: anotherClass.b
};
}
}
But I'm getting this error message.
Property 'getCopy' is missing in type '{ a: number; b: number; }' but required in type 'myClass'
Why is it thinking getCopy() is a property? I have C# background and C# does not require to initialize functions. Is there a way to create a class instance and initialize properties without initializing functions? I'm looking for an easier way like C# code below.
var newInstance = new myClass()
{
a = 1,
b = 2
};
Instead of doing like this.
var newInstance = new myClass();
newInstance.a = 1;
newInstance.b = 2;
Or is this not possible with typescript?
Upvotes: 1
Views: 569
Reputation: 12796
I don't really think you need a class for the code you provided, just describe your datastructure in an interface, say
interface DataStructure {
a: number;
b: string;
}
and then create an object which has these properties, say:
const instance: DataStructure = { a: 5, b: 'test' };
You can then use the interface as well as parameters for your functions or return values. It doesn't have to be a class, so for example:
function someFunction( b: DataStructure): void {
}
someFunction(instance); // works
someFunction({a: 10, b: 'test'}); // works
someFunction({a: 10}); // doesn't work, b is required
Upvotes: 0
Reputation: 191749
getCopy
is a property of myClass. You are declaring it as a property of myClass. An instance of myClass
could also be written using Object notation:
const myClassInstance = {
a,
b,
getCopy,
}
Since getCopy
is not optional on myClass
, you must have this property and it must match the type of the myClass
delcaration, so it must be a function.
All that being said, it's not entirely clear to me why you need an instance method that creates a copy of the class. You could just have this as a standalone function instead. Cloning the top level of an object can also be done in a few different ways including the spread operator, so you generally don't need to write your own function to do this either.
const myClass = new myClass();
myClass.a = 1
myClass.b = 2;
const myClassCopy = { ...myClass };
Upvotes: 1
Reputation: 96
Create new clone instance of myClass class:
public getCopy(anotherClass: myClass): myClass {
return Object.assign(new myClass(), {...});
}
Upvotes: 1