This post has been de-listed
It is no longer included in search results and normal feeds (front page, hot posts, subreddit posts, etc). It remains visible only via the author's post history.
Noob here, so go easy on me. I'm learning generics, and I found a piece of sample code on the TypeScript website that will not compile. The page is here (https://www.typescriptlang.org/docs/handbook/2/generics.html), under Generic Classes, and the code is:
class GenericNumber<NumType> {
zeroValue: NumType;
add: (x: NumType, y: NumType) => NumType;
}
let myGenericNumber = new GenericNumber<number>();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function (x, y) {
return x y;
};
I copied this code into the website's online compiler (https://www.typescriptlang.org/play) and got 2 errors in the class definition: Property 'zeroValue' has no initializer and is not definitely assigned in the constructor.
and Property 'add' has no initializer and is not definitely assigned in the constructor.
Can anyone explain why this is wrong and why TypeScript's own manual would include code that doesn't work? I'm guessing the manual must be behind the latest version of TS. In any case, I get that the compiler is demanding I initialize the class members, but how would you do that? You can't just say zeroValue: NumType = 0;
, it'll complain that the Number 0 is not a NumType.
Subreddit
Post Details
- Posted
- 1 year ago
- Reddit URL
- View post on reddit.com
- External URL
- reddit.com/r/typescript/...