Back to questions
JuniorTheoryCommon
What does tsc report for this code?
class Counter {
count: number;
step: number = 1;
}
const c = new Counter();
console.log(c.count, c.step);An error: the field count has no initial value
- Expecting
countto be leftundefinedas in JavaScript: strict mode requires every field to get a value in its declaration or in the constructor, andcountgets neither. - Expecting a number field to start at
0: TypeScript adds no default values, so without an initializer the field would holdundefined.
- Which changes to the class make this error go away?
- Why does an assignment inside an
ifin the constructor not count?