Property types
- TypeScript course
- Beginner
- Lesson 52/89
- 4 min
Learn to type interface properties.
Property types
Each property in an interface has a type. You can use string, number, boolean, arrays, or even other interfaces. Properties are separated by semicolons.
interface Urun {
ad: string;
fiyat: number;
stokta: boolean;
}Each property determines the type of the object's corresponding value.
Optional and readonly in interfaces
Interfaces support optional (?) and readonly properties just like object types. Optional properties may be absent; readonly properties cannot be changed after creation.
interface Urun {
readonly id: number;
ad: string;
etiketler?: string[];
}An interface supports all features of object types.
Practice Interface with various property types
Define an interface named Urun with properties ad: string, fiyat: number, and stokta: boolean. Declare a variable named urun of type Urun with value { ad: "kalem", fiyat: 15, stokta: true }. Print the value of urun.fiyat with console.log.
Starter code
// Urun adında bir interface tanımla
// ad (string), fiyat (number), stokta (boolean) özellikleri içersin
// urun değişkenini Urun türünde tanımla
// değer: ad "kalem", fiyat 15, stokta true
// urun.fiyat değerini yazdırSample solution
interface Urun {
ad: string;
fiyat: number;
stokta: boolean;
}
let urun: Urun = { ad: "kalem", fiyat: 15, stokta: true };
console.log(urun.fiyat);Expected output
15
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 In <code>interface Urun { ad: string; fiyat: number; stokta: boolean }</code>, what is the type of the <code>fiyat</code> property?
- Urun
- string
- boolean
- number Correct answer
Explanation: Since the interface definition writes <code>fiyat: number</code>, the type of the <code>fiyat</code> property is <code>number</code>.
2 Complete the property type
interface Urun {
ad: string;
fiyat: number;
stokta: ____;
}
interface Urun {
ad: string;
fiyat: number;
stokta: boolean;
}
Explanation: The <code>stokta</code> property indicates whether a product is in stock; the correct type is <code>boolean</code>. <code>string</code> and <code>number</code> are wrong for a yes/no state, and <code>void</code> is not a property type.
3 Property types concepts
| Term | Meaning |
|---|---|
ad: string (interface) |
String property |
fiyat: number (interface) |
Number property |
etiketler?: string[] |
Optional array property |
readonly id: number |
Readonly property |