Interface vs type alias
- TypeScript course
- Beginner
- Lesson 53/89
- 4 min
Learn the difference between Interface and type alias.
Interface vs type alias
Both interface and type can define object shapes. interface is specifically for objects and can be extended. type is more general; it can also define unions and primitives.
// interface
interface Kisi { ad: string; yas: number; }
// type alias
type Nokta = { x: number; y: number };Both can be used for simple object shapes.
When to use interface and type?
interface is preferred for object shapes that may be extended. type is used for union types, intersection types, or primitive aliases. Both work for object shapes.
// interface can be extended
interface Hayvan { ad: string }
interface Kedi extends Hayvan { miyav: string }Choose interface or type based on the need.
Practice Interface and type alias together
Define an interface named Kisi with properties ad: string and yas: number. Define a type alias named Nokta ({ x: number; y: number }). Declare a variable named kisi of type Kisi with value { ad: "Veli", yas: 30 }. Print the value of kisi.ad with console.log.
Starter code
// Kisi adında bir interface tanımla (ad: string, yas: number)
// Nokta adında bir type alias tanımla (x: number, y: number)
// kisi değişkenini Kisi türünde tanımla, değer: { ad: "Veli", yas: 30 }
// kisi.ad değerini yazdırSample solution
interface Kisi {
ad: string;
yas: number;
}
type Nokta = { x: number; y: number };
let kisi: Kisi = { ad: "Veli", yas: 30 };
console.log(kisi.ad);Expected output
Veli
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is specifically designed for object shapes?
- type
- const
- interface Correct answer
- let
Explanation: The <code>interface</code> keyword is specifically designed for defining object shapes; <code>type</code> is more general and can also define union types.
2 Add the correct keyword
____ Kisi { ad: string; yas: number; }
interface Kisi { ad: string; yas: number; }
Explanation: The <code>interface</code> keyword defines an object shape with curly braces; <code>type</code> requires an equals sign, <code>class</code> is a different concept, and <code>object</code> is invalid in this syntax.
3 Interface vs type concepts
| Term | Meaning |
|---|---|
interface X { ... } |
Specific for object shapes |
type X = { ... } |
General type definition |
type X = string | number |
Union type (type only) |
interface vs type |
Interface is specific to objects |