Consider this TypeScript class with typed properties and a method. What will be printed when the code runs?
class Person { name: string; age: number; constructor(name: string, age: number) { this.name = name; this.age = age; } greet(): string { return `Hello, my name is ${this.name} and I am ${this.age} years old.`; } } const p = new Person("Alice", 30); console.log(p.greet());
Look at how the constructor assigns values to the typed properties.
The class Person has typed properties name and age. The constructor sets these correctly. The greet method returns a string using these properties. So the output is the greeting with the given name and age.
Which of the following best explains why typed classes are important in TypeScript?
Think about what types help with before running the code.
Typed classes help developers catch mistakes early by checking that properties and methods are used with the correct types. This reduces bugs and improves code quality.
Examine this TypeScript class code. What error will occur when compiling?
class Car { model: string; year: number; constructor(model: string) { this.model = model; } getAge(currentYear: number): number { return currentYear - this.year; } }
Check if all typed properties are assigned values in the constructor.
The property year is declared but never assigned a value in the constructor or with a default. TypeScript requires all properties to be initialized or marked optional.
Choose the correct TypeScript class definition where id is a readonly number property set in the constructor.
Remember the correct order of modifiers and types in TypeScript.
The correct syntax places readonly before the property name and type. Option B follows this rule.
Given this TypeScript class and instance, how many own properties does the instance book have?
class Book { title: string; author: string; static category: string = "Literature"; constructor(title: string, author: string) { this.title = title; this.author = author; } } const book = new Book("1984", "George Orwell"); const count = Object.keys(book).length; console.log(count);
Static properties are not part of instance own properties.
The instance book has two own properties: title and author. The static property category belongs to the class, not the instance.