Consider this TypeScript code using duck typing. What will be printed?
interface Quack {
quack(): void;
}
function makeItQuack(duck: Quack) {
duck.quack();
}
const notADuck = {
quack: () => console.log('I am quacking!')
};
makeItQuack(notADuck);Duck typing means the object just needs to have the right shape, not the exact type.
The object notADuck has a quack method, so it matches the Quack interface. TypeScript allows this, so the function runs and prints the message.
Choose the best description of duck typing in TypeScript.
Think about how TypeScript compares object shapes rather than names.
TypeScript uses structural typing, meaning it compares the shape (properties and methods) of objects rather than their explicit names or inheritance.
Look at this code snippet. Why does TypeScript report an error?
interface Flyer {
fly(): void;
}
const bird = {
fly: () => console.log('Flying'),
swim: () => console.log('Swimming')
};
function makeFly(f: Flyer) {
f.fly();
}
makeFly({swim: () => console.log('Swimming')});Check if the object passed has the required method.
The object passed to makeFly only has a swim method but no fly method. TypeScript requires the object to have all properties of the interface.
Given this interface, which object correctly matches it by duck typing?
interface Runner {
run(speed: number): string;
}Check the method signature matches the interface exactly.
Option C matches the interface exactly: run takes a number and returns a string. Option C misses the parameter type, C uses wrong parameter type, and D has no parameter.
result after this duck typing code runs?Analyze the code and find the value of result.
interface Speaker {
speak(): string;
}
const obj1 = { speak: () => 'Hello' };
const obj2 = { speak: () => 'World' };
function combineSpeakers(a: Speaker, b: Speaker): string {
return a.speak() + ' ' + b.speak();
}
const result = combineSpeakers(obj1, obj2);Both objects have a speak method returning strings.
Both obj1 and obj2 match the Speaker interface by duck typing. The function concatenates their speak results with a space.