Consider this TypeScript class with typed constructor parameters. What will be the output when creating an instance and logging its properties?
class Person { name: string; age: number; constructor(name: string, age: number) { this.name = name; this.age = age; } } const p = new Person('Alice', 30); console.log(`${p.name} is ${p.age} years old.`);
Check how the constructor assigns the parameters to the class properties.
The constructor correctly assigns the name and age parameters to the class properties. So logging them outputs the expected string.
What error will TypeScript show for this class when trying to create an instance?
class Car { model: string; year: number; constructor(model: string, year: number) { this.model = model; this.year = year; } } const c = new Car('Tesla', '2020');
Look at the type of the second argument passed to the constructor.
The constructor expects year to be a number, but a string is passed. TypeScript reports a type mismatch error.
Examine the class and its constructor. Why does this code cause a runtime error?
class Rectangle { width: number; height: number; constructor(width: number, height: number) { this.width = width; // Forgot to assign height } area() { return this.width * this.height; } } const r = new Rectangle(5, 10); console.log(r.area());
Check if all properties are initialized before use.
The height property is never assigned a value, so it is undefined. Multiplying a number by undefined results in NaN.
Which option correctly uses TypeScript's parameter properties to declare and initialize class members in the constructor?
Parameter properties combine declaration and assignment in the constructor parameters.
Option D correctly declares x and y as class members with access modifiers in the constructor parameters. Other options have syntax errors or misuse.
Given this TypeScript class using parameter properties and explicit members, how many own properties will an instance have?
class User { id: number; constructor(public name: string, id: number) { this.id = id; } } const u = new User('Bob', 42); console.log(Object.keys(u).length);
Parameter properties create class members that are own properties. Explicit assignments also create own properties.
The instance u has two own properties: name (from parameter property) and id (assigned in constructor). So Object.keys(u).length is 2.