Alias vs interface
- TypeScript course
- Beginner
- Lesson 57/89
- 4 min
Learn the distinction between type alias and interface.
Alias vs interface
Both type and interface can define object shapes. However, type is more general: it can define unions, primitives, and tuples. interface is for objects and can be extended with extends.
// union with type
type ID = number | string;
// object with interface
interface Kisi { ad: string }Type is more general; interface is specific to objects.
When to use alias and interface?
Use type for union types, intersection types, primitives, and tuples. Use interface for object shapes that may be extended or merged. Both work for simple object shapes.
// type: union and tuple
type ID = number | string;
type Nokta = [number, number];
// interface: extensible object
interface Hayvan { ad: string }Choose type or interface based on the need.
Practice Use type and interface together
Define a type alias named ID (number | string union). Define an interface named Kisi with properties ad: string and id: ID. Declare a variable named kisi of type Kisi with value { ad: "Ali", id: 42 }. Print the value of kisi.ad with console.log.
Starter code
// ID adında bir type alias tanımla (number | string birleşimi)
// Kisi adında bir interface tanımla (ad: string, id: ID)
// kisi değişkenini Kisi türünde tanımla, değer: { ad: "Ali", id: 42 }
// kisi.ad değerini yazdırSample solution
type ID = number | string;
interface Kisi {
ad: string;
id: ID;
}
let kisi: Kisi = { ad: "Ali", id: 42 };
console.log(kisi.ad);Expected output
Ali
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which can define a union type?
- const
- class
- interface
- type Correct answer
Explanation: The <code>type</code> keyword can define union types (<code>type X = A | B</code>); <code>interface</code> only defines object shapes and does not support unions.
2 Add the second half of the union type
type ID = number | ____;
type ID = number | string;
Explanation: Since an ID can be both a number and a string, the union must be <code>number | string</code>; <code>boolean</code> makes no sense for an ID, <code>void</code> is not a value type, and <code>number</code> is a duplicate.
3 Alias vs interface concepts
| Term | Meaning |
|---|---|
type X = string | number |
Union type (type only) |
interface X { ... } |
Object shape (extensible) |
type X = string |
Primitive type alias |
Alias vs interface |
Type is more general |