Issue
I am learning typescript,this code is related to Generics(Generic classes) and exists in docs of typescript.what is the problem?
class GenericNumber
{
zeroValue: T;
add: (x: T, y: T) => T;
}
let myGenericNumber = new GenericNumber();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function(x, y)
{
return x + y;
};
error:Property 'zeroValue' has no initializer and is not definitely assigned in the constructor.ts(2564)
Solution
first of all the best way to share your TypeScript code is to publish it on TypeScript playground
I think you are talking about this example
// you missed generic initializer
class GenericNumber<T> { // you missed generic initializer
// here TS compiler throws error because you only defined a type of class
// property, but you did not initialize it
zeroValue: T;
add: (x: T, y: T) => T;
}
let myGenericNumber = new GenericNumber<number>(); // you missed generic initializer
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function (x, y) {
return x + y; // no error
};
Working example
class GenericNumber<T> {
// to get rid of error, you can define constructor
// which takes [zeroValue] and [add] as arguments
constructor(public zeroValue: T, public add: (x: T, y: T) => T){
this.zeroValue = zeroValue;
this.add = add;
}
}
const zeroValue = 0;
let myGenericNumber = new GenericNumber<number>(zeroValue, (a,b)=>a+b);
const result = myGenericNumber.add(40,2) // 42
Make sure your function don't deal with this, because in that case you should handle it
Answered By - captain-yossarian
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.