Summary - Interfaces
- TypeScript course
- Beginner
- Lesson 54/89
- 4 min
Write a product catalog model with interfaces.
Summary - Interfaces
Interfaces define object shapes as contracts, give types to properties (including optional and readonly), and are a tool specific to objects. Compared to type, interface is specific to objects and can be extended.
interface Urun {
readonly id: number;
ad: string;
fiyat?: number;
}These features together create powerful and flexible data models.
Practice Product catalog model
Define an interface named Urun with properties readonly id: number, ad: string, and fiyat?: number. Declare a variable named urun of type Urun with value { id: 1, ad: "defter", fiyat: 20 }. Print the value of urun.ad with console.log.
Starter code
// Urun adında bir interface tanımla
// readonly id (number), ad (string), fiyat? (number) özellikleri içersin
// urun değişkenini Urun türünde tanımla
// değer: id 1, ad "defter", fiyat 20
// urun.ad değerini yazdırSample solution
interface Urun {
readonly id: number;
ad: string;
fiyat?: number;
}
let urun: Urun = { id: 1, ad: "defter", fiyat: 20 };
console.log(urun.ad);Expected output
defter
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When should <code>interface</code> be preferred over <code>type</code>?
- When defining a primitive alias
- When describing an object shape that may be extended Correct answer
- When defining an intersection type
- When defining a union type
Explanation: <code>interface</code> is preferred for object shapes that may be extended (<code>extends</code>); union and intersection types can only be defined with <code>type</code>.
2 Complete the optional property type
interface Urun {
readonly id: number;
ad: string;
fiyat?: ____;
}
interface Urun {
readonly id: number;
ad: string;
fiyat?: number;
}
Explanation: A product price is a number; <code>fiyat?: number</code> is the correct completion. <code>string</code> and <code>boolean</code> are wrong types for a price, and <code>void</code> is not a property type.
3 Interface summary
| Term | Meaning |
|---|---|
interface X { ... } |
Object shape contract |
ad?: string |
Skippable property |
readonly id: number |
Fixed after first assignment |
interface vs type |
Interface can be extended |