0
0
Typescriptprogramming~5 mins

Duck typing mental model in TypeScript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is duck typing in TypeScript?
Duck typing means that if an object has all the required properties and methods, it is considered to be of that type, regardless of its actual class or inheritance.
Click to reveal answer
beginner
How does TypeScript check types with duck typing?
TypeScript checks if an object has the necessary shape (properties and methods) to match a type, not if it explicitly declares that type.
Click to reveal answer
beginner
Example: If an object has a 'name' string property and a 'speak()' method, can it be used where a type with those members is expected?
Yes, because the object matches the shape required by the type, TypeScript allows it even if the object does not explicitly implement that type.
Click to reveal answer
intermediate
Why is duck typing useful in TypeScript?
It allows flexible and easy code reuse by focusing on what an object can do rather than its exact type or class.
Click to reveal answer
intermediate
Can duck typing cause errors if an object has extra properties?
No, TypeScript allows extra properties as long as the required ones exist, but excess property checks apply in some cases like object literals.
Click to reveal answer
In TypeScript, what does duck typing check for?
AIf an object is explicitly declared with a type
BIf an object inherits from a specific class
CIf an object has the required properties and methods
DIf an object has no extra properties
Which of these is true about duck typing in TypeScript?
AAn object must explicitly implement an interface to be valid
BTypeScript does not allow extra properties in objects
CDuck typing requires inheritance
DAn object with matching properties can be used even without explicit implementation
What happens if an object literal has extra properties not in the expected type?
ATypeScript always allows it
BTypeScript gives an error due to excess property checks
CTypeScript ignores extra properties silently
DThe object is automatically cast to the expected type
Why is duck typing called that way?
ABecause if it looks like a duck and quacks like a duck, it is treated as a duck
BBecause it uses ducks in examples
CBecause it requires inheritance from a Duck class
DBecause it only works with animals
Which TypeScript feature relies on duck typing?
AStructural typing
BNominal typing
CClass inheritance
DType casting
Explain the duck typing mental model in TypeScript and how it affects type checking.
Think about how TypeScript decides if an object fits a type.
You got /4 concepts.
    Describe a situation where duck typing in TypeScript can cause an error and why.
    Consider when you write an object literal with more properties than expected.
    You got /4 concepts.