0
0
Typescriptprogramming~20 mins

Static members with types in Typescript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Static Member Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of accessing static member

What is the output of this TypeScript code?

Typescript
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);
A0
B2
C1
Dundefined
Attempts:
2 left
💡 Hint

Remember static members belong to the class, not instances.

🧠 Conceptual
intermediate
1:30remaining
Type of static member

Which of the following correctly declares a static member with a type in TypeScript?

Astatic name: string = "App";
Bname: static string = "App";
Cstatic name = string "App";
Dstatic string name = "App";
Attempts:
2 left
💡 Hint

Static members use the static keyword before the name, then the type annotation.

🔧 Debug
advanced
2:00remaining
Why does this code cause an error?

Consider this TypeScript code snippet:

class Example {
  static value: number;
  constructor() {
    this.value = 5;
  }
}

Why does this code cause an error?

AConstructor cannot be declared in a class with static members
BStatic members must be initialized outside the class
CStatic members cannot be numbers
D"this" cannot be used to access static members inside constructor
Attempts:
2 left
💡 Hint

Think about how static members belong to the class, not instances.

📝 Syntax
advanced
1:30remaining
Identify the syntax error in static member declaration

Which option contains a syntax error when declaring a static member in TypeScript?

Astatic count: number = 0;
Bstatic readonly count: number = 0;
Cstatic count number = 0;
Dstatic count = 0;
Attempts:
2 left
💡 Hint

Check the order of type annotation and variable name.

🚀 Application
expert
2:30remaining
Count instances using static member

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());
A3
B0
C1
Dundefined
Attempts:
2 left
💡 Hint

Static members keep track of data shared by all instances.