'Property 'zeroValue' has no initializer and is not definitely assigned in the constructor

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 1:[1]

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

Solution 2:[2]

You can disable this typescript features in the following ways.

If you are using TypeScript playground, go to TS Config and uncheck the strictPropertyInitialization.

If you are using typescript in your project, in tsconfig.json file, disable this feature by setting "strictPropertyInitialization": false.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 captain-yossarian from Ukraine
Solution 2