Lesson 28 of 55
9 mins readPython Type Synonyms (type) & newtype Wrappers
In Plain English
Use type to create descriptive aliases for existing types (e.g. type Point = (Double, Double)). Use newtype for zero-overhead type-safe single-constructor wrappers.
Deep Dive: How It Works
type Synonyms: type PhoneNumber = String creates a readable alias; interchangeable with String.
newtype Wrappers: newtype USD = USD Double creates a distinct type at compile time that is erased at runtime, guaranteeing zero performance overhead.
Type Safety: newtype prevents accidentally mixing up currencies or measurement units.
Core Rules to Remember

type for Readability: type Matrix = [[Double]] documents complex types clearly.

newtype for Zero-Cost Safety: Guarantees distinct type safety without heap allocation penalty.
Live Interactive Example
Hit Run Code to see it livetype and newtype in Practice
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Output Console
Click "Run Code" to view the rendered output.
How it works: Coord is a synonym for (Double, Double). USD is a distinct newtype.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Define CustomerId newtype
Define `newtype CustomerId = CustomerId Int deriving (Show)`.
Create `c = CustomerId 1001` and print `"Customer: "` followed by `show c`.
1
2
3
4
5
6
7
8
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.