SlideShare a Scribd company logo
Communicating Intention
with Functional TypeScript
Communicating Intention with Functional TypeScript
Communicating Intention with Functional TypeScript
Communicating Intention with Functional TypeScript
What don’t you like
about TypeScript?
Communicating Intention with Functional TypeScript
λ
+
!101
Thiago Temple
Software Engineer
@SurveyMonkey
Communicating Intention with Functional TypeScript
Communicating Intention with Functional TypeScript
Communicating Intention with Functional TypeScript
Function
Signatures
The Any
Type
Strings
Invalid
Object
States
Immutability
What is This Function
Doing?
Function Signatures
Communicating Intention with Functional TypeScript
function add(n1: number, n2: number) { }
function processOrder(order: Order, options: Orde
Communicating Intention with Functional TypeScript
type OrderResult =
ProcessedOrder |
OrderAction |
string;
function processOrder
( order: Order,
options: OrderOptions): OrderResult {
type OrderResult =
ProcessedOrder |
OrderAction |
string;
type OrderProcessingError = string;
type OrderResult =
ProcessedOrder |
OrderAction |
string;
type OrderProcessingError = string;
type OrderResult =
ProcessedOrder |
OrderAction |
OrderProcessingError;
Error Handling
function processOrder
( order: Order,
options: OrderOptions) {
Avoiding Throwing Exceptions
type Result<TResult, TError> =
Success<TResult> |
Failure<TError>;
type Success<T> = {
kind: "successfulResult";
value: T;
};
type Failure<T> = {
kind: "failedResult";
error: T;
};
type OrderResult =
Result<ProcessedOrder | OrderAction,
OrderProcessingError>;
function processOrder(
order: Order,
options: OrderOptions): OrderResult {
type OrderResult =
Result<ProcessedOrder | OrderAction,
OrderProcessingError>;
function processOrder(
order: Order,
options: OrderOptions): OrderResult {
type OrderResult =
Result<ProcessedOrder | OrderAction,
OrderProcessingError>;
function processOrder(
order: Order,
options: OrderOptions): OrderResult {
const result =
processOrder(order, orderOptions);
if (result.kind === "failedResult") {
result.error;
// OrderProcessingError A.K.A. string
} else {
result.value;
// ProcessedOrder | OrderAction
}
null
• Not Found
• An Error Has Occurred
• Unpredicted Case
• Something is Not Required
• Condition as False-y
• And More…
Versatile
Don’t Use null
function findUserById(id: string):
User | null {
type Option<T> =
Some<T> | None;
type Some<T> = {
kind: "someOption";
value: T;
};
type None = {
kind: "noneOption";
}
type Option<T> =
Some<T> | None;
function findUserById(id: string):
Option<User> {
const user =
findUserById(userId);
if (user.kind === "someOption") {
user.value; // User
}
Any What?
–Thiago Temple
“Don’t use any as a catch-all for types you’re unsure
of, also, don’t be lazy.”
Valid Uses of any
• When you know nothing about the given value
• When you don’t care about the given value
unknown
function exec(args: unknown) {
args["someKey"] // Compile Error
}
function exec<T extends { someKey: string }>(args: T) {
args["someKey"] // OK
}
const val1 = lib.someFun();
lib2.otherFunc(val1);
// Err: val2 is of != type
const val1: any = lib.someFun();
lib2.otherFunc(val1);
const val1 = lib.someFun();
lib2.otherFunc(val1 as any);
L
I
M
I
T
I
N
G
S
T
R
I
N
G
S
function findByGenre(genre: string): Movie[]
type Genre =
"Drama" |
"Comedy" |
"Action";
function findByGenre(genre: Genre): Movie[] {
type OrderStatus =
"New" |
"Paid" |
"Shipped" |
"Completed";
type Order = {
status: OrderStatus
// ...
};
function processOrder(order: Order): Order {
switch(order.status) {
case "New":
return ...;
case "Paid":
return ...;
case "Shipped":
return ...;
case "Completed":
return ...;
}
}
function processOrder(order: Order): Order {
switch(order.status) {
case "New":
return ...;
case "Paid":
return ...;
case "Shipped":
return ...;
case "Completed":
return ...;
}
}
nvalid States Impossible to Re
type Payment = {
amount: number;
creditCardInfo?: CreditCardInfo;
payPalInfo?: PayPalInfo;
cash: boolean;
}
const payment: Payment = {
amount: 42,
cash: false
};
type Payment = {
amount: number;
paymentInfo: PaymentInfo;
}
type PaymentInfo =
CreditCardInfo |
PayPalInfo |
Cash;
type CreditCardInfo = {
kind: "creditCardInfo";
// ...
};
type PayPalInfo = {
kind: "payPalInfo";
// ...
};
type Cash = {
kind: "cash";
}
const payment: Payment = {
amount: 42,
paymentInfo: {
kind: "creditCardInfo",
number: 12321312312312312312312
}
};
type Order = {
orderId: string;
billingAddress: Address;
shippingAddress?: Address;
};
type Order = {
orderId: string;
billingAddress: Address;
shipping: ShippingInfo;
};
type ShippingInfo =
SameAsBilling |
DownloadableContent |
ShippingAddress;
type SameAsBilling = {
kind: "sameAsBilling";
}
type DownloadableContent = {
kind: "downloadableContent";
}
type ShippingAddress = {
kind: "shippingAddress";
address: Address;
}
ShippingResult {
switch(order.shipping.kind) {
case "downloadableContent":
return ...;
case "sameAsBilling":
return ...;
case "shippingAddress":
order.shipping.address; // Address
ShippingResult {
switch(order.shipping.kind) {
case "downloadableContent":
return ...;
case "sameAsBilling":
return ...;
case "shippingAddress":
order.shipping.address; // Address
ShippingResult {
switch(order.shipping.kind) {
case "downloadableContent":
return ...;
case "sameAsBilling":
return ...;
case "shippingAddress":
order.shipping.address; // Address
ShippingResult {
switch(order.shipping.kind) {
case "downloadableContent":
return ...;
case "sameAsBilling":
return ...;
case "shippingAddress":
order.shipping.address; // Address
ShippingResult {
switch(order.shipping.kind) {
case "downloadableContent":
return ...;
case "sameAsBilling":
return ...;
case "shippingAddress":
order.shipping.address; // Address
What Happened With my Data
Communicating Intention with Functional TypeScript
Communicating Intention with Functional TypeScript
function processOrders(orders: readonly Order[]) {
orders.push({...}) // Error
orders.pop() // Error
orders.reverse() // Error
}
function processOrders(order: readonly Order) {
function processOrders
(order: Readonly<Order>) {
order.orderId = 123; // Error
order.customer.customerId = 123; // OK
}
type Immutable<T> = {
readonly [K in keyof T]: Immutable<T[K]>;
}
type Order = Immutable<{
orderId: string;
customer: Customer;
billingAddress: Address;
shipping: ShippingInfo;
}>;
function processOrder(order: Immutable<Order>)
function processOrder(order: Immutable<Order>) {
order.orderId = ""; // Error
order.customer.customerId = ""; // Error
order.shipping = { kind: "sameAsBilling" }; // Error
}
Final Thoughts and
Recap
Compiled Code Doesn’t Get Stale
Think About The Next Person
(and yourself)
nest About Your Function Sign
Be Mindful With Your Use of any
Limit the Scope of Strings
nvalid States Impossible to Re
surveymonkey.com/careers
Thank You
@ThiagoTemple

More Related Content

PDF
Антон Молдован "Type driven development with f#"
PPT
Sql 2005 the ranking functions
PDF
JavaScript: Variables and Functions
PDF
Test driven development
PDF
LeakChecker: Practical Static Memory Leak Detection for Managed Languages
PDF
05 communications
PPTX
Functional DDD
ODP
Simple design/programming nuggets
Антон Молдован "Type driven development with f#"
Sql 2005 the ranking functions
JavaScript: Variables and Functions
Test driven development
LeakChecker: Practical Static Memory Leak Detection for Managed Languages
05 communications
Functional DDD
Simple design/programming nuggets

Similar to Communicating Intention with Functional TypeScript (16)

PPTX
Type Driven Development with TypeScript
PPTX
How Reactive do we need to be
PPTX
Working effectively with legacy code
PDF
help me Java projectI put problem and my own code in the linkmy .pdf
PDF
Redux Action Creators
PPTX
Andriy Slobodyanyk "How to Use Hibernate: Key Problems and Solutions"
PPTX
Clean Code: Chapter 3 Function
PPTX
Improving Correctness with Types
PDF
Controle de estado
PDF
Structure on a freeform world
PPTX
Improving Correctness With Type - Goto Con Berlin
PPTX
Javascript ch7
PDF
Clean coding-practices
PDF
Introduction to typescript
PDF
Are statecharts the next big UI paradigm?
DOC
Marcus Portfolio
Type Driven Development with TypeScript
How Reactive do we need to be
Working effectively with legacy code
help me Java projectI put problem and my own code in the linkmy .pdf
Redux Action Creators
Andriy Slobodyanyk "How to Use Hibernate: Key Problems and Solutions"
Clean Code: Chapter 3 Function
Improving Correctness with Types
Controle de estado
Structure on a freeform world
Improving Correctness With Type - Goto Con Berlin
Javascript ch7
Clean coding-practices
Introduction to typescript
Are statecharts the next big UI paradigm?
Marcus Portfolio
Ad

Recently uploaded (20)

PDF
Approach and Philosophy of On baking technology
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Empathic Computing: Creating Shared Understanding
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Encapsulation theory and applications.pdf
PPTX
sap open course for s4hana steps from ECC to s4
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPT
Teaching material agriculture food technology
Approach and Philosophy of On baking technology
20250228 LYD VKU AI Blended-Learning.pptx
Empathic Computing: Creating Shared Understanding
Building Integrated photovoltaic BIPV_UPV.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
MYSQL Presentation for SQL database connectivity
Dropbox Q2 2025 Financial Results & Investor Presentation
Unlocking AI with Model Context Protocol (MCP)
Chapter 3 Spatial Domain Image Processing.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
Spectral efficient network and resource selection model in 5G networks
NewMind AI Weekly Chronicles - August'25 Week I
Encapsulation theory and applications.pdf
sap open course for s4hana steps from ECC to s4
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Programs and apps: productivity, graphics, security and other tools
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Teaching material agriculture food technology
Ad

Communicating Intention with Functional TypeScript