Consider this TypeScript code that uses an object type to define a person's details. What will be printed to the console?
type Person = { name: string; age: number };
const person: Person = { name: "Alice", age: 30 };
console.log(`Name: ${person.name}, Age: ${person.age}`);Look at how the object person is created and how its properties are accessed.
The object person has properties name and age correctly assigned. Accessing these properties prints their values.
Which of the following best explains why object types are needed in TypeScript?
Think about what TypeScript adds on top of JavaScript regarding objects.
Object types let TypeScript know what properties an object should have and their types, helping catch mistakes early.
Look at this code snippet. What error will TypeScript show?
type Car = { make: string; year: number };
const myCar: Car = { make: "Toyota" };
console.log(myCar.year);Check if all required properties are present when creating myCar.
The object assigned to myCar is missing the required year property, so TypeScript reports an error.
In TypeScript, how do you define an object type where the property middleName is optional?
Look for the correct syntax to mark a property as optional in TypeScript.
The question mark ? after the property name marks it as optional in TypeScript object types.
Given this TypeScript code, how many properties does the user object have when the program runs?
type User = { id: number; name: string; email?: string };
const user: User = { id: 1, name: "Bob" };
if (user.email) {
console.log(user.email);
}Optional properties may or may not exist on the object at runtime depending on assignment.
The user object has only id and name properties assigned. The optional email is not present, so total is 2.