What is the output of the following TypeScript code?
interface Animal {
speak(): string;
}
class Dog implements Animal {
speak(): string {
return "Woof!";
}
}
class Cat implements Animal {
speak(): string {
return "Meow!";
}
}
function makeSpeak(animal: Animal) {
console.log(animal.speak());
}
const dog = new Dog();
const cat = new Cat();
makeSpeak(dog);
makeSpeak(cat);Look at which class instance is passed to makeSpeak and what speak() returns.
The makeSpeak function calls the speak() method of the passed Animal instance. Since dog is a Dog instance, it returns "Woof!". The cat instance returns "Meow!".
Which statement best describes polymorphism through interfaces in TypeScript?
Think about how different classes can share the same method names but behave differently.
Polymorphism through interfaces means that multiple classes implement the same interface but provide their own unique behavior for the interface's methods.
What error will this TypeScript code produce when run?
interface Shape {
area(): number;
}
class Rectangle implements Shape {
constructor(public width: number, public height: number) {}
area(): number {
return this.width * this.height;
}
}
class Circle implements Shape {
constructor(public radius: number) {}
area(): number {
return Math.PI * this.radius * this.radius;
}
}
const shapes: Shape[] = [new Rectangle(5, 10), new Circle(3)];
shapes.forEach(shape => {
if (shape instanceof Rectangle) {
console.log(shape.area());
} else {
console.log(shape.diameter());
}
});Check if all methods called on shape exist in the classes.
The Circle class does not have a diameter() method, so calling shape.diameter() causes a runtime TypeError.
Which option correctly implements the Vehicle interface with a move() method?
interface Vehicle {
move(): string;
}Check the method signature and return type matching the interface.
Option C correctly implements move() returning a string as required. Option C uses incorrect syntax for method implementation. Option C returns void instead of string. Option C returns undefined because it logs but does not return a string.
Given the following code, what is the output?
interface Logger {
log(message: string): string;
}
class ConsoleLogger implements Logger {
log(message: string): string {
return `Console: ${message}`;
}
}
class FileLogger implements Logger {
log(message: string): string {
return `File: ${message}`;
}
}
function processLoggers(loggers: Logger[], msg: string): string[] {
return loggers.map(logger => logger.log(msg));
}
const loggers: Logger[] = [new ConsoleLogger(), new FileLogger()];
const results = processLoggers(loggers, "Test message");
console.log(results.join(", "));Look at the order of loggers in the array and what their log methods return.
The processLoggers function calls log on each logger in order. The first is ConsoleLogger returning "Console: Test message", the second is FileLogger returning "File: Test message". The output joins these with a comma and space.