SlideShare a Scribd company logo
Communicating Intention
with Functional TypeScript
What don’t you like
about TypeScript?
λ
+
!101
Thiago Temple
Software Engineer
@SurveyMonkey
Function
Signatures
The Any
Type
Strings
Invalid
Object
States
Immutability
What is This Function
Doing?
Function Signatures
function add(n1: number, n2: number) { }
function processOrder(order: Order, options: Orde
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
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

Similar to Communicating Intention with Functional TypeScript

Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScript
Garth Gilmour
 
How Reactive do we need to be
How Reactive do we need to beHow Reactive do we need to be
How Reactive do we need to be
Jana Karceska
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy code
ShriKant Vashishtha
 
help me Java projectI put problem and my own code in the linkmy .pdf
help me Java projectI put problem and my own code in the linkmy .pdfhelp me Java projectI put problem and my own code in the linkmy .pdf
help me Java projectI put problem and my own code in the linkmy .pdf
arihantmum
 
Redux Action Creators
Redux Action CreatorsRedux Action Creators
Redux Action Creators
Konstantins Starovoitovs
 
Andriy Slobodyanyk "How to Use Hibernate: Key Problems and Solutions"
Andriy Slobodyanyk "How to Use Hibernate: Key Problems and Solutions"Andriy Slobodyanyk "How to Use Hibernate: Key Problems and Solutions"
Andriy Slobodyanyk "How to Use Hibernate: Key Problems and Solutions"
LogeekNightUkraine
 
Clean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionClean Code: Chapter 3 Function
Clean Code: Chapter 3 Function
Kent Huang
 
Improving Correctness with Types
Improving Correctness with TypesImproving Correctness with Types
Improving Correctness with Types
Iain Hull
 
Controle de estado
Controle de estadoControle de estado
Controle de estado
Bruno Bilescky
 
Structure on a freeform world
Structure on a freeform worldStructure on a freeform world
Structure on a freeform world
Ikai (藍奕凱) Lan
 
Improving Correctness With Type - Goto Con Berlin
Improving Correctness With Type - Goto Con BerlinImproving Correctness With Type - Goto Con Berlin
Improving Correctness With Type - Goto Con Berlin
Iain Hull
 
Javascript ch7
Javascript ch7Javascript ch7
Javascript ch7
Brady Cheng
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
John Ferguson Smart Limited
 
Introduction to typescript
Introduction to typescriptIntroduction to typescript
Introduction to typescript
Mario Alexandro Santini
 
Are statecharts the next big UI paradigm?
Are statecharts the next big UI paradigm? Are statecharts the next big UI paradigm?
Are statecharts the next big UI paradigm?
Luca Matteis
 
Marcus Portfolio
Marcus  PortfolioMarcus  Portfolio
Marcus Portfolio
marobertson22
 

Similar to Communicating Intention with Functional TypeScript (16)

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

Recently uploaded

Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
Zilliz
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
Neo4j
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
Claudio Di Ciccio
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
IndexBug
 

Recently uploaded (20)

Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
 

Communicating Intention with Functional TypeScript