0
0
Typescriptprogramming~10 mins

Duck typing mental model in TypeScript - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define an object that matches the interface by duck typing.

Typescript
interface Bird {
  fly(): void;
}

const duck: Bird = {
  [1]() {
    console.log('Flying');
  }
};
Drag options to blanks, or click blank then click option'
Aswim
Bfly
Cwalk
Drun
Attempts:
3 left
💡 Hint
Common Mistakes
Using a method name different from the interface, like 'swim' or 'walk'.
2fill in blank
medium

Complete the code to assign an object with extra properties to a variable typed by an interface.

Typescript
interface Person {
  name: string;
}

const user: Person = {
  name: 'Alice',
  [1]: 30
};
Drag options to blanks, or click blank then click option'
Aheight
Baddress
Cweight
Dage
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to omit the required property name.
Using a property name that conflicts with the interface.
3fill in blank
hard

Fix the error by completing the code to match the interface using duck typing.

Typescript
interface Logger {
  log(message: string): void;
}

const consoleLogger: Logger = {
  [1](msg: string) {
    console.log(msg);
  }
};
Drag options to blanks, or click blank then click option'
Aprint
Boutput
Clog
Dwrite
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different method name like 'print' or 'write' causes a type error.
4fill in blank
hard

Fill both blanks to create a function that accepts any object with a 'speak' method and calls it.

Typescript
function makeSpeak(obj: { [1](): void }) {
  obj.[2]();
}
Drag options to blanks, or click blank then click option'
Aspeak
Btalk
Csay
Dshout
Attempts:
3 left
💡 Hint
Common Mistakes
Using different method names in the parameter and call causes errors.
5fill in blank
hard

Fill all three blanks to create a duck-typed object with a method and an extra property.

Typescript
interface Animal {
  [1](): void;
}

const cat: Animal = {
  [2]() {
    console.log('Meow');
  },
  [3]: 'black'
};
Drag options to blanks, or click blank then click option'
AmakeSound
Ccolor
Dsize
Attempts:
3 left
💡 Hint
Common Mistakes
Using a method name different from the interface.
Using an extra property name not intended for this example.