Optional properties
- TypeScript course
- Beginner
- Lesson 39/89
- 4 min
Learn optional properties with ?.
Optional properties
Some properties may not always be present. You make them optional by placing ? after the property name. An optional property may or may not be present in the object.
let kisi: { ad: string; tel?: string } = {
ad: "Ali"
}; // tel missing, validWith ? a property becomes optional and can be omitted.
Accessing optional properties
When you access an optional property, its value may be undefined if not set. It is safe to check whether it is defined before using it.
let kisi: { ad: string; tel?: string } = {
ad: "Ali"
};
console.log(kisi.tel); // undefinedOptional properties may have the value undefined.
Practice Object with an optional property
Declare a variable named kisi with type { ad: string; tel?: string } and value { ad: "Can", tel: "555" }. Print the value of kisi.tel with console.log.
Starter code
// kisi adında bir nesne tanımla
// ad özelliği zorunlu dize, tel özelliği isteğe bağlı dize olsun
// ad değeri "Can", tel değeri "555" olsun
// kisi.tel değerini yazdırSample solution
let kisi: { ad: string; tel?: string } = { ad: "Can", tel: "555" };
console.log(kisi.tel);Expected output
555
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does <code>tel?: string</code> mean?
- tel property cannot be assigned
- tel property is optional and may be absent Correct answer
- tel property is of type number
- tel property must be a string
Explanation: The <code>?</code> mark makes a property optional; <code>tel?: string</code> means the <code>tel</code> property may or may not be present.
2 Make the property optional
let urun: { ad: string; indirim____: number } = { ad: "kalem" };
let urun: { ad: string; indirim?: number } = { ad: "kalem" };
Explanation: Since the value does not include <code>indirim</code>, the property must be optional; the <code>?</code> mark enables this and allows the missing property.
3 Optional property concepts
| Term | Meaning |
|---|---|
tel?: string |
Optional string property |
tel: string |
Required string property |
? (özellik adından sonra) |
Makes a property optional |
Optional property |
Property may be absent |