0
0
Typescriptprogramming~20 mins

Declaring functions and classes in Typescript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Function and Class Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a class method call
What is the output of this TypeScript code?
Typescript
class Greeter {
  greeting: string;
  constructor(message: string) {
    this.greeting = message;
  }
  greet() {
    return `Hello, ${this.greeting}`;
  }
}

const greeter = new Greeter("world");
console.log(greeter.greet());
AError: Property 'greeting' does not exist
BHello, undefined
CHello, world
DHello, message
Attempts:
2 left
💡 Hint
Look at how the constructor sets the greeting property and how greet() uses it.
Predict Output
intermediate
1:30remaining
Function return type and output
What will this TypeScript function return when called with argument 5?
Typescript
function multiplyByTwo(x: number): number {
  return x * 2;
}

console.log(multiplyByTwo(5));
A10
B"10"
Cundefined
DError: Function must return a string
Attempts:
2 left
💡 Hint
Check the function's return statement and the argument passed.
🔧 Debug
advanced
2:30remaining
Identify the error in this class declaration
What error does this TypeScript code produce?
Typescript
class Person {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
  greet(): void {
    console.log('Hello, ' + this.names);
  }
}

const p = new Person('Alice');
p.greet();
ATypeError: Cannot read property 'names' of undefined
BSyntaxError: Unexpected token
Cundefined
DReferenceError: names is not defined
Attempts:
2 left
💡 Hint
Check the property name used inside the greet method.
📝 Syntax
advanced
2:00remaining
Which option declares a valid function with default parameter?
Which of the following TypeScript function declarations is syntactically correct and sets a default value for parameter 'count'?
Afunction repeat(text: string, count?: number = 3): string { return text.repeat(count); }
Bfunction repeat(text: string, count = 3): string { return text.repeat(count); }
Cfunction repeat(text: string, count: number = 3?) { return text.repeat(count); }
Dfunction repeat(text: string, count = 3?) { return text.repeat(count); }
Attempts:
2 left
💡 Hint
Default parameters are assigned with '=' without '?' after the parameter name.
🚀 Application
expert
3:00remaining
Class inheritance and method overriding output
What is the output of this TypeScript code?
Typescript
class Animal {
  speak(): string {
    return 'Generic sound';
  }
}

class Dog extends Animal {
  speak(): string {
    return 'Woof';
  }
}

const pet: Animal = new Dog();
console.log(pet.speak());
AError: Method speak not found
BGeneric sound
Cundefined
DWoof
Attempts:
2 left
💡 Hint
Think about which speak method runs when a Dog instance is assigned to an Animal type variable.