0
0
Typescriptprogramming~20 mins

Duck typing mental model in TypeScript - Mini Project: Build & Apply

Choose your learning style9 modes available
Duck typing mental model in TypeScript
📖 Scenario: Imagine you are building a simple system to check if different objects can be treated as a bird based on their behavior, not their exact type. This is like recognizing a bird by its ability to quack and fly, even if it is not a real bird.
🎯 Goal: You will create objects with different properties and use TypeScript's duck typing to check if they can be treated as birds by having the right methods. You will then print messages confirming which objects behave like birds.
📋 What You'll Learn
Create two objects with different properties but both have quack and fly methods.
Create a type alias called Bird that requires quack and fly methods.
Write a function called makeItFly that accepts a parameter of type Bird and calls its quack and fly methods.
Call makeItFly with both objects and print the results.
💡 Why This Matters
🌍 Real World
Duck typing helps in real-world programming when you want to use objects that behave the same way without forcing them to share a class or inheritance.
💼 Career
Understanding duck typing is important for TypeScript developers to write flexible and reusable code that works with different objects sharing the same behavior.
Progress0 / 4 steps
1
Create two objects with quack and fly methods
Create two objects called duck and toyDuck. Both should have a quack method that returns the string "Quack!" and a fly method that returns the string "Flying!". The duck object should also have a property isReal set to true. The toyDuck object should have a property material set to "plastic".
Typescript
Need a hint?

Remember to create two objects with the exact names duck and toyDuck. Both need quack and fly methods returning the exact strings.

2
Create a Bird type alias
Create a type alias called Bird that requires two methods: quack and fly. Both methods should return a string.
Typescript
Need a hint?

Use type Bird = { quack: () => string; fly: () => string; } exactly.

3
Write a function that accepts Bird type
Write a function called makeItFly that accepts one parameter called bird of type Bird. Inside the function, call bird.quack() and bird.fly() and return a string combining both results separated by a space.
Typescript
Need a hint?

Define makeItFly with parameter bird: Bird and return the combined string.

4
Call makeItFly with both objects and print results
Call makeItFly with duck and print the result using console.log. Then call makeItFly with toyDuck and print the result using console.log.
Typescript
Need a hint?

Use console.log(makeItFly(duck)) and console.log(makeItFly(toyDuck)) to print the results.