Summary - Objects
- TypeScript course
- Beginner
- Lesson 41/89
- 4 min
Write a user card by combining object types.
Summary - Objects
Object types let you model data precisely: shape defines properties, ? marks optional properties, and readonly marks immutable properties. Together they create safe and clear data structures.
let kullanici: {
readonly id: number;
ad: string;
eposta?: string
} = { id: 1, ad: "Ali" };These three features together create flexible but safe object types.
Practice Write a user card
Declare a variable named kullanici with type { readonly id: number; ad: string; eposta?: string } and value { id: 1, ad: "Zeynep", eposta: "z@x.com" }. Print the value of kullanici.eposta with console.log.
Starter code
// kullanici adında bir nesne tanımla
// id özelliği readonly sayı, ad özelliği zorunlu dize, eposta özelliği isteğe bağlı dize olsun
// id değeri 1, ad değeri "Zeynep", eposta değeri "z@x.com" olsun
// kullanici.eposta değerini yazdırSample solution
let kullanici: { readonly id: number; ad: string; eposta?: string } = { id: 1, ad: "Zeynep", eposta: "z@x.com" };
console.log(kullanici.eposta);Expected output
z@x.com
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which type allows the value <code>{ ad: "Ali" }</code> but prevents reassigning <code>ad</code>?
- { readonly ad: string } Correct answer
- { ad: string; tel?: string }
- { readonly id: number; ad: string }
- { ad?: string }
Explanation: <code>{ readonly ad: string }</code> makes <code>ad</code> both required and immutable; the value <code>{ ad: "Ali" }</code> is valid and <code>ad</code> cannot be changed later.
2 Complete the optional property type
let kullanici: { readonly id: number; ad: string; eposta?: ____ } = { id: 1, ad: "Ali" };
let kullanici: { readonly id: number; ad: string; eposta?: string } = { id: 1, ad: "Ali" };
Explanation: Since <code>eposta</code> is an email address, its type must be <code>string</code>; <code>number</code> and <code>boolean</code> are wrong types for an email, and <code>void</code> is not a property type.
3 Object concepts summary
| Term | Meaning |
|---|---|
{ ad: string } |
Required property |
tel?: string |
Optional property |
readonly id: number |
Immutable property |
Object type |
Object shape |