What is the output of this TypeScript code?
class Counter { static count: number = 0; increment() { Counter.count++; } } const c1 = new Counter(); c1.increment(); const c2 = new Counter(); c2.increment(); console.log(Counter.count);
Remember static members belong to the class, not instances.
Static member count is shared across all instances. Each increment() call increases the same count. After two increments, Counter.count is 2.
Which of the following correctly declares a static member with a type in TypeScript?
Static members use the static keyword before the name, then the type annotation.
Option A uses correct TypeScript syntax: static name: string = "App";. Other options have invalid order or keywords.
Consider this TypeScript code snippet:
class Example {
static value: number;
constructor() {
this.value = 5;
}
}Why does this code cause an error?
Think about how static members belong to the class, not instances.
Static members belong to the class itself, so inside instance methods or constructor, this refers to the instance, not the class. To access static members, use the class name.
Which option contains a syntax error when declaring a static member in TypeScript?
Check the order of type annotation and variable name.
Option C is invalid because it misses the colon between the variable name and type. Correct syntax is count: number.
What will be the value of InstanceCounter.getCount() after creating three instances?
class InstanceCounter {
private static count: number = 0;
constructor() {
InstanceCounter.count++;
}
static getCount(): number {
return InstanceCounter.count;
}
}
const a = new InstanceCounter();
const b = new InstanceCounter();
const c = new InstanceCounter();
console.log(InstanceCounter.getCount());Static members keep track of data shared by all instances.
Each time the constructor runs, it increments the static count. After three instances, count is 3.