0
0
Typescriptprogramming~5 mins

What structural typing means in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is structural typing in TypeScript?
Structural typing means that TypeScript checks if two types are compatible based on their shape or structure, not their names. If the properties and types match, they are considered compatible.
Click to reveal answer
intermediate
How does structural typing differ from nominal typing?
Structural typing compares the actual content (properties and methods) of types, while nominal typing compares types by their names or explicit declarations.
Click to reveal answer
beginner
Example: Are these two types compatible in TypeScript?<br>
type A = { name: string };
type B = { name: string; age: number };
No, type A is not assignable to type B because it lacks the 'age' property. However, type B is assignable to type A because it has all required properties of A plus extra ones, which are allowed in structural typing.
Click to reveal answer
beginner
Why is structural typing useful in TypeScript?
It allows flexible and easy code reuse by focusing on what data looks like rather than what it is called. This helps when working with different objects that share the same shape.
Click to reveal answer
intermediate
Can two different classes be compatible in TypeScript under structural typing?
Yes, if their public properties and methods match in shape, TypeScript considers them compatible even if they come from different classes.
Click to reveal answer
What does structural typing check in TypeScript?
AThe names of types
BThe shape or structure of types
CThe file location of types
DThe order of declaration
If two objects have the same properties and types, TypeScript considers them:
AIncompatible
BOnly compatible if declared with the same name
COnly compatible if from the same class
DCompatible
Which typing system compares types by their names rather than structure?
AStructural typing
BDuck typing
CNominal typing
DDynamic typing
In TypeScript, can an object with extra properties be assigned to a type with fewer properties?
AYes, if the required properties match
BNo, extra properties cause errors
COnly if explicitly cast
DOnly if using interfaces
Structural typing helps TypeScript by:
AFocusing on data shape for compatibility
BMaking code less flexible
CRequiring explicit type names
DPreventing object reuse
Explain in your own words what structural typing means in TypeScript and why it matters.
Think about how two objects with the same properties can be used interchangeably.
You got /3 concepts.
    Describe a real-life example where structural typing helps when working with different objects.
    Imagine two different forms that have the same fields.
    You got /3 concepts.