0% found this document useful (0 votes)
14 views5 pages

Unit 4

Interfaces in TypeScript define a contract for the structure of objects, specifying required properties, methods, and events for type-checking. Duck Typing allows an object to be treated as an interface if it possesses the required properties and methods, regardless of its name or inheritance. An example demonstrates that an object with additional properties can still be valid as long as it meets the interface's requirements.

Uploaded by

Navya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views5 pages

Unit 4

Interfaces in TypeScript define a contract for the structure of objects, specifying required properties, methods, and events for type-checking. Duck Typing allows an object to be treated as an interface if it possesses the required properties and methods, regardless of its name or inheritance. An example demonstrates that an object with additional properties can still be valid as long as it meets the interface's requirements.

Uploaded by

Navya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

4. What are interfaces in Type Script. Explain about Duck Typing with an example.

Interfaces in TypeScript

An interface is a structure that defines the contract in your application.


It defines the syntax that any entity must adhere to.

Interfaces define properties, methods, and events, which are the members of the interface.

 It is a way to define type-checking in TypeScript.

 Interfaces help in validating the structure of the object.

✅ Duck Typing in TypeScript

Duck Typing is a dynamic typing style used in TypeScript, where the type of an object is determined
by its present properties or methods, not by its name or inheritance.

If an object "walks like a duck and quacks like a duck", it’s considered a duck.

This means:
If an object has all the required properties and methods, it is treated as that interface, even if it's
not explicitly using the interface.

✅ Duck Typing Example:

interface Person {

firstName: string;

lastName: string;

function printName(person: Person) {

console.log(person.firstName + " " + person.lastName);

let myObj = {

firstName: "Steve",

lastName: "Rogers",

age: 25

printName(myObj); // ✅ Valid because it has all required properties

Even though myObj has an extra property age, it is accepted as Person type because it has both
firstName and lastName — this is duck typing.

You might also like