0
0
Typescriptprogramming~10 mins

Optional properties in Typescript - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare an optional property age in the interface.

Typescript
interface Person {
  name: string;
  age[1]: number;
}
Drag options to blanks, or click blank then click option'
A!
B?
C:
D;
Attempts:
3 left
💡 Hint
Common Mistakes
Using colon : instead of question mark ? after the property name.
Forgetting to add any symbol after the property name.
2fill in blank
medium

Complete the code to create an object that may or may not have the optional property age.

Typescript
const user: Person = {
  name: "Alice",
  [1]
};
Drag options to blanks, or click blank then click option'
Aage: 30
Bage?
Cage;
Dage = 30
Attempts:
3 left
💡 Hint
Common Mistakes
Using age? in object literal, which is invalid syntax.
Using assignment = inside object literal.
3fill in blank
hard

Fix the error in the interface by correctly marking email as optional.

Typescript
interface Contact {
  phone: string;
  email[1]: string;
}
Drag options to blanks, or click blank then click option'
A!
B:
C?
D;
Attempts:
3 left
💡 Hint
Common Mistakes
Using colon : instead of question mark ? for optional properties.
Using exclamation mark ! which is for definite assignment assertion, not optional.
4fill in blank
hard

Complete the code to create a function parameter with an optional property middleName.

Typescript
function greet(person: { firstName: string; middleName[1]: string; }) {
  console.log(`Hello, ${person.firstName}`);
}
Drag options to blanks, or click blank then click option'
A?
B;
C,
D:
Attempts:
3 left
💡 Hint
Common Mistakes
Using colon : instead of semicolon to separate properties.
Forgetting the question mark for optional property.
5fill in blank
hard

Fill both blanks to define an interface with optional properties and use it in an object.

Typescript
interface Book {
  title: string;
  author[1]: string;
  year[2]: number;
}

const myBook: Book = {
  title: "1984",
  author: "George Orwell"
};
Drag options to blanks, or click blank then click option'
A?
B;
D:
Attempts:
3 left
💡 Hint
Common Mistakes
Using colon : instead of question mark ? for optional properties.
Missing semicolons after properties.