Coming soon - Get a detailed view of why an account is flagged as spam!
view details

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.

1
TypeScript website's own manual has an example code that won't compile
Post Body

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.

Author
Account Strength
100%
Account Age
7 years
Verified Email
Yes
Verified Flair
No
Total Karma
5,125
Link Karma
983
Comment Karma
4,129
Profile updated: 3 days ago
Posts updated: 7 hours ago

Subreddit

Post Details

We try to extract some basic information from the post title. This is not always successful or accurate, please use your best judgement and compare these values to the post title and body for confirmation.
Posted
1 year ago