Complete the code to declare an optional property age in the interface.
interface Person {
name: string;
age[1]: number;
}: instead of question mark ? after the property name.In TypeScript, adding a ? after the property name makes it optional.
Complete the code to create an object that may or may not have the optional property age.
const user: Person = {
name: "Alice",
[1]
};age? in object literal, which is invalid syntax.= inside object literal.When creating an object, optional properties can be included like normal properties with a value.
Fix the error in the interface by correctly marking email as optional.
interface Contact {
phone: string;
email[1]: string;
}: instead of question mark ? for optional properties.! which is for definite assignment assertion, not optional.The question mark ? after email marks it as optional.
Complete the code to create a function parameter with an optional property middleName.
function greet(person: { firstName: string; middleName[1]: string; }) {
console.log(`Hello, ${person.firstName}`);
}: instead of semicolon to separate properties.The question mark ? marks middleName as optional, and the semicolon ; separates properties.
Fill both blanks to define an interface with optional properties and use it in an object.
interface Book {
title: string;
author[1]: string;
year[2]: number;
}
const myBook: Book = {
title: "1984",
author: "George Orwell"
};: instead of question mark ? for optional properties.The author property is optional with ? and ends with a semicolon ;. The year property is optional and ends with a semicolon.