Which statement best describes what structural typing means in TypeScript?
Think about how TypeScript compares objects based on their shape, not their names.
Structural typing means that TypeScript checks if types have the same shape (properties and methods) to decide compatibility, ignoring explicit names or inheritance.
What is the output of this TypeScript code?
interface Point { x: number; y: number; }
function printPoint(p: Point) {
console.log(`x: ${p.x}, y: ${p.y}`);
}
const pointLike = { x: 10, y: 20, z: 30 };
printPoint(pointLike);Remember TypeScript allows extra properties when passing objects if required properties exist.
The object has at least the properties x and y required by Point, so it is accepted. Extra properties like z are ignored.
Consider this code snippet. Why does it cause a TypeScript error?
interface Animal { name: string; }
interface Dog extends Animal { bark(): void; }
function makeAnimalBark(animal: Dog) {
animal.bark();
}
const myAnimal = { name: 'Buddy' };
makeAnimalBark(myAnimal);Check if the object passed has all required properties and methods.
Structural typing requires the object to have all properties and methods of the target type. 'myAnimal' lacks 'bark', so it causes an error.
Choose the code snippet that correctly uses structural typing to assign one object to another type.
Remember that a type with more properties can be assigned to a type with fewer properties if the required ones match.
Option D assigns a bigger type (B) to a smaller type (A), which is allowed by structural typing. Other options either assign smaller to bigger or have errors.
What will be the output when running this TypeScript code?
type FuncA = (x: number) => number; type FuncB = (x: number, y: number) => number; const f1: FuncA = (x) => x * 2; const f2: FuncB = (x, y) => x + y; const test1: FuncA = f2; const test2: FuncB = f1; console.log(test1(5)); console.log(test2(5, 10));
Think about function parameter compatibility in structural typing.
In TypeScript, a function with fewer parameters can be assigned to a type expecting more parameters, but not vice versa. Assigning f1 (one param) to FuncB (two params) causes a compile error.