SlideShare a Scribd company logo
Static Types on Javascript!?
Type-checking approaches to ensure healthy applications
(Tipos estáticos em Javascript?! Abordagens de type-checking para garantir uma aplicação saudável)
Arthur Puthin
About me
Developer at ilegra (think beyond!)
Mostly front-end stuff
Undergraduate at Unisinos
@aputhin
@aputhin_
https://twitter.com/nodejspoa/status/929339757947170816
So, what is this all about?
- Types
- JS Types
- Why (or why not) Static Types
- How to Static Types
Agenda
Actually, I just want to give you food for thought on
Javascript typing, dynamic or static, and not champion
any approach in particular
Data Types 101
Data types define, among other stuff:
A set from which the data
may take its' value
The operations that can be
performed on/with the data
Values
add, subtract, multiply, divide
concat, substr
and, or, xor, not
Operations
-∞ … -2, -1, 0, 1, 2, 3, 4 … +∞
abcdefghijklmnopqrstuvwxyz
true, false
Primitive types are basic
data types which are usually
built-in for each language
Composite or complex
types are derived from
more than one primitive,
and can be user-defined
Programming languages' type systems may apply:
Static type checking, which
happens at compile time
and validates variables'
types
Dynamic type checking,
which happens at runtime
and validates types for data
itself
Data Types: the JS Way
In JavaScript, variables
don't have types -- values
have types. [...] Another way
to think about JS types is
that JS doesn't have "type
enforcement" [...].
https://github.com/getify/You-Dont-Know-JS/blob/master/types%20%26%20grammar/ch1.md
let a = 42;
typeof a; // "number"
a = true;
typeof a; // "boolean"
Primitives
- null
- undefined
- boolean
- number
- string
- symbol (ES2015)
IMMUTABLE
ASSIGN BY COPY
let a = 41;
let b = a;
b++;
console.log(a); // 41
console.log(b); // 42
Object Type
- objects of any shape
- functions
- arrays let a = [1, 2];
let b = a;
b.push(3);
console.log(a); // [1, 2, 3]
console.log(b); // [1, 2, 3]
b = [4, 5, 6];
console.log(a); // [1, 2, 3]
console.log(b); // [4, 5, 6]
MUTABLE
ASSIGN BY REFERENCE
let c = { isC: true };
let d = c;
d.isC = false;
console.log(c); // { isC: false }
console.log(d); // { isC: false }
Native Object Types
- String()
- Number()
- Boolean()
- Array()
- Object()
- Function()
- RegExp()
- Date()
- Error()
- ...
const a = 'string';
const b = new String('string');
typeof a; // string
typeof b; // object
const c = a.split('', 3); // auto-boxing
Primitive Wrappers
Type coercion in Javascript can be:
Implicit, when the runtime
itself performs conversions,
usually engaged to satisfy the
surrounding context
Explicit (a.k.a. type-casting),
when the developer
expresses the intention to
convert between types by
writing the appropriate code
String conversion
Boolean(2) // explicit
if (2) { /**/ } // implicit
!!2 // implicit
2 || 'hello' // implicit
Boolean('') // false
Boolean(0) // false
Boolean(-0) // false
Boolean(NaN) // false
Boolean(null) // false
Boolean(undefined) // false
Boolean(false) // false
// everything else is true!
https://medium.freecodecamp.org/js-type-coercion-explained-27ba3d9a2839
Boolean conversion
String(123) // explicit
123 + '' // implicit
String(123) // '123'
String(-12.3) // '-12.3'
String(null) // 'null'
String(undefined) // 'undefined'
String(true) // 'true'
String(false) // 'false'
Number conversion
https://medium.freecodecamp.org/js-type-coercion-explained-27ba3d9a2839
Number('123') // explicit
+'123' // implicit (unary operator +)
123 != '456' // implicit (loose equality operator == !=)
// except if both operands are strings!
4 > '5' // implicit (comparison operators > < <= >=)
true | 0 // implicit (bitwise operators | & ^ ~)
5/null // implicit (arithmetic operators - + * / %)
// except for + if either operand is a string!
Object to Primitive Conversion
1. If input is already a primitive, do nothing and return it.
2. Call input.toString(), if the result is primitive, return it.
3. Call input.valueOf(), if the result is primitive, return it.
4. If neither input.toString() nor input.valueOf() yields
primitive, throw TypeError.
https://medium.freecodecamp.org/js-type-coercion-explained-27ba3d9a2839
Be a responsible and mature developer.
Learn how to use the power of coercion
(both explicit and implicit) effectively and
safely. And teach those around you to do the
same.
https://github.com/getify/You-Dont-Know-JS/blob/master/types%20%26%20grammar/ch4.md
https://twitter.com/codepo8/status/986305494368292864?s=19
Why would we go static?
"The most often-cited rationales for
type systems are that they:
1. Catch errors early
2. Improve readability of code
3. Facilitate tooling
4. Improve runtime performance"
http://www.hammerlab.org/2015/12/09/our-experiences-with-flow/
● It takes time to learn.
● It is an additional layer of complexity.
● It constrains your freedom of expression.
● It does not prevent defects.
● You lose some interactivity and compiling
takes time.
http://2ality.com/2018/03/javascript-typescript-reasonml.html
https://twitter.com/JofArnold/status/974574921509634049
Static Typing options
1. Supersets
2. Static Type Checkers
3. Compile-to-JS
http://www.typescriptlang.org/
Who's using it?
http://www.typescriptlang.org/community/friends.html
tsc
webpack (ts-loader)
babel (babel-preset-typescript)
gulp (gulp-typescript)
browserify (tsify)
let isDone: boolean = false;
let answer: number = 42; // includes hex, binary and octal
let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length; // type casting
let anotherLength: number = (someValue as string).length;
function warnUser(): void { // null or undefined
alert("This is my warning message");
}
let list1: number[] = [1, 2, 3];
let list2: Array<number> = [1, 2, 3];
let x: [string, number];
x = ["hello", 10]; // OK
x = [10, "hello"]; // Error
enum Color {Red, Green, Blue}
let c: Color = Color.Green; // 2
let colorName: string = Color[2]; // Blue
interface Record {
readonly id: number;
label: string;
color?: string; // optional prop
}
class Greeter {
private greeting: string;
public constructor(message: string) {
this.greeting = message;
}
}
let greeter = new Greeter("world");
// module exporting types and namespacing
export namespace Validation {
export interface StringValidator {
isAcceptable(s: string): boolean;
}
}
// checking normal js files with --checkJs flag
/** @type {number} */
var x;
x = false; // error
flow-remove-types
babel (babel-preset-flow)
gulp (gulp-flowtype)
browserify (unflowify)
// @flow
const answer: number = 42;
const indexes: Array<number> = [0, 1, 2]; // Array<T>
let whatever: any; // wildcard
whatever = 'string';
whatever = true;
const func = (arg: number): number => {/*...*/}; // return type, optional
// @flow
const identity: { name: string, age: number } = {
name: 'Jack',
age: 15,
};
type Address = { street: string, number: number };
type Email = string; // aliasing
var message: ?string = null; // maybe: type, null or undef
function setValue(value?: string) {/*...*/} // optional: type or undef
// @flow
type MyObject<A, B> = { foo: A, bar: B };
const val: MyObject<number, boolean> = { foo: 1, bar: true };
function getColor(name: "success" | "warning" | "danger") {/*...*/}
type Foo = { foo: number };
type Bar = { bar: boolean };
let value: Foo & Bar = { foo: 1, bar: true };
http://elm-lang.org/
Who's using it?
http://elm-lang.org/
elm-make
divide : Float -> Float -> Float
divide x y =
x / y
type alias User =
{ name : String, bio : String, pic : String }
hasBio : User -> Bool
hasBio user =
String.length user.bio > 0
-- alias auto-generates constructors for you :)
User "Tom" "Friendly Carpenter" "http://example.com/tom.jpg"
type Visibility = All | Active | Completed -- union type
keep : Visibility -> List Task -> List Task
keep visibility tasks =
case visibility of -- has to cover all possibilities!
All ->
tasks
Active ->
List.filter (task -> not task.complete) tasks
Completed ->
List.filter (task -> task.complete) tasks
toFullName person = person.firstName ++ " " ++ person.lastName
fullName = toFullName { fistName = "Hermann", lastName = "Hesse" }
The argument to function `toFullName` is causing a mismatch.
6│ toFullName { fistName = "Hermann", lastName = "Hesse" }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Function `toFullName` is expecting the argument to be:
{ …, firstName : … }
But it is:
{ …, fistName : … }
Hint: I compared the record fields and found some potential typos.
firstName <-> fistName
https://reasonml.github.io/
Who's using it?
https://reasonml.github.io/en/users-of-reason.html
bsb
let myInt = 5; /* inferred integer */
let myInt: int = 5; /* explicit definition */
let myInt = (5: int) + (4: int); /* definition mid-expression */
/* params and return types */
let add = (x: int, y: int) : int => x + y;
let drawCircle = (~radius as r: int, ~color as c: string) => {
setColor(c);
startAt(r, r);
/* ... */
};
/* type aliases */
type scoreType = int;
let x: scoreType = 10;
/* parameterized type */
type coordinates('a) = ('a, 'a, 'a);
type intCoordinatesAlias = coordinates(int); /* new type is created */
let buddy: intCoordinatesAlias = (10, 20, 20); /* new type is used */
let buddy: coordinates(float) = (10.5, 20.5, 20.5); /* inline flavor */
/* Mutually Recursive Types */
type student = {taughtBy: teacher} and teacher = {students: list(student)};
Takeaways
Despite the tradeoffs that come with types like
verbosity and the upfront investment to master them,
the safety and correctness that types add to our
programs make these “disadvantages” less of an issue
for me personally.
https://medium.freecodecamp.org/why-use-static-types-in-javascript-part-4-b2e1e06a67c9
Static typing or not is an emotional topic. My advice is:
● Use whatever makes you happy and productive.
● Do acknowledge both strengths and weaknesses of
what you are using.
http://2ality.com/2018/03/javascript-typescript-reasonml.html
Try stuff out, understand how each
approach works and teach people
around you!
Thanks for your time!
@aputhin @aputhin_

More Related Content

What's hot

Python idiomatico
Python idiomaticoPython idiomatico
Python idiomatico
PyCon Italia
 
C++ Presentation
C++ PresentationC++ Presentation
C++ Presentation
Carson Wilber
 
Vocabulary Types in C++17
Vocabulary Types in C++17Vocabulary Types in C++17
Vocabulary Types in C++17
Bartlomiej Filipek
 
Os Goodger
Os GoodgerOs Goodger
Os Goodger
oscon2007
 
Safer JS Codebases with Flow
Safer JS Codebases with FlowSafer JS Codebases with Flow
Safer JS Codebases with Flow
Valentin Agachi
 
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
LogeekNightUkraine
 
Template Haskell
Template HaskellTemplate Haskell
Template Haskell
Sergey Stretovich
 
Big Brother helps you
Big Brother helps youBig Brother helps you
Big Brother helps you
PVS-Studio
 
C++17 std::filesystem - Overview
C++17 std::filesystem - OverviewC++17 std::filesystem - Overview
C++17 std::filesystem - Overview
Bartlomiej Filipek
 
C# / Java Language Comparison
C# / Java Language ComparisonC# / Java Language Comparison
C# / Java Language Comparison
Robert Bachmann
 
Workhop iOS 1: Fundamentos de Swift
Workhop iOS 1: Fundamentos de SwiftWorkhop iOS 1: Fundamentos de Swift
Workhop iOS 1: Fundamentos de Swift
Visual Engineering
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
Raghavan Mohan
 
JavaScript 1 for high school
JavaScript 1 for high schoolJavaScript 1 for high school
JavaScript 1 for high school
jekkilekki
 
Cocoa for Web Developers
Cocoa for Web DevelopersCocoa for Web Developers
Cocoa for Web Developers
georgebrock
 
Groovy presentation
Groovy presentationGroovy presentation
Groovy presentation
Manav Prasad
 
Hack programming language
Hack programming languageHack programming language
Hack programming language
Radu Murzea
 
C Programming Assignment
C Programming AssignmentC Programming Assignment
C Programming Assignment
Vijayananda Mohire
 
All You Need to Know About Type Script
All You Need to Know About Type ScriptAll You Need to Know About Type Script
All You Need to Know About Type Script
Folio3 Software
 
Programming with Python - Adv.
Programming with Python - Adv.Programming with Python - Adv.
Programming with Python - Adv.
Mosky Liu
 
Assignment c programming
Assignment c programmingAssignment c programming
Assignment c programming
Icaii Infotech
 

What's hot (20)

Python idiomatico
Python idiomaticoPython idiomatico
Python idiomatico
 
C++ Presentation
C++ PresentationC++ Presentation
C++ Presentation
 
Vocabulary Types in C++17
Vocabulary Types in C++17Vocabulary Types in C++17
Vocabulary Types in C++17
 
Os Goodger
Os GoodgerOs Goodger
Os Goodger
 
Safer JS Codebases with Flow
Safer JS Codebases with FlowSafer JS Codebases with Flow
Safer JS Codebases with Flow
 
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
 
Template Haskell
Template HaskellTemplate Haskell
Template Haskell
 
Big Brother helps you
Big Brother helps youBig Brother helps you
Big Brother helps you
 
C++17 std::filesystem - Overview
C++17 std::filesystem - OverviewC++17 std::filesystem - Overview
C++17 std::filesystem - Overview
 
C# / Java Language Comparison
C# / Java Language ComparisonC# / Java Language Comparison
C# / Java Language Comparison
 
Workhop iOS 1: Fundamentos de Swift
Workhop iOS 1: Fundamentos de SwiftWorkhop iOS 1: Fundamentos de Swift
Workhop iOS 1: Fundamentos de Swift
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
 
JavaScript 1 for high school
JavaScript 1 for high schoolJavaScript 1 for high school
JavaScript 1 for high school
 
Cocoa for Web Developers
Cocoa for Web DevelopersCocoa for Web Developers
Cocoa for Web Developers
 
Groovy presentation
Groovy presentationGroovy presentation
Groovy presentation
 
Hack programming language
Hack programming languageHack programming language
Hack programming language
 
C Programming Assignment
C Programming AssignmentC Programming Assignment
C Programming Assignment
 
All You Need to Know About Type Script
All You Need to Know About Type ScriptAll You Need to Know About Type Script
All You Need to Know About Type Script
 
Programming with Python - Adv.
Programming with Python - Adv.Programming with Python - Adv.
Programming with Python - Adv.
 
Assignment c programming
Assignment c programmingAssignment c programming
Assignment c programming
 

Similar to Static types on javascript?! Type checking approaches to ensure healthy applications

Clean & Typechecked JS
Clean & Typechecked JSClean & Typechecked JS
Clean & Typechecked JS
Arthur Puthin
 
2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws
loffenauer
 
JavaScript for Web Analysts
JavaScript for Web AnalystsJavaScript for Web Analysts
JavaScript for Web Analysts
Lukáš Čech
 
Functions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupFunctions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrup
SyedHaroonShah4
 
C programming(part 3)
C programming(part 3)C programming(part 3)
C programming(part 3)
SURBHI SAROHA
 
Stuff you didn't know about action script
Stuff you didn't know about action scriptStuff you didn't know about action script
Stuff you didn't know about action script
Christophe Herreman
 
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
Doug Jones
 
Ajax and JavaScript Bootcamp
Ajax and JavaScript BootcampAjax and JavaScript Bootcamp
Ajax and JavaScript Bootcamp
AndreCharland
 
C++ boot camp part 1/2
C++ boot camp part 1/2C++ boot camp part 1/2
C++ boot camp part 1/2
Jesse Talavera-Greenberg
 
C++ Boot Camp Part 1
C++ Boot Camp Part 1C++ Boot Camp Part 1
C++ Boot Camp Part 1
Jesse Talavera-Greenberg
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
Intro C# Book
 
Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1
Troy Miles
 
Kotlin
KotlinKotlin
Kotlin
BoKaiRuan
 
Javascript status 2016
Javascript status 2016Javascript status 2016
Javascript status 2016
Arshavski Alexander
 
Programming with Java: the Basics
Programming with Java: the BasicsProgramming with Java: the Basics
Programming with Java: the Basics
Jussi Pohjolainen
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
javaTpoint s
 
Type script - advanced usage and practices
Type script  - advanced usage and practicesType script  - advanced usage and practices
Type script - advanced usage and practices
Iwan van der Kleijn
 
From android/java to swift (3)
From android/java to swift (3)From android/java to swift (3)
From android/java to swift (3)
allanh0526
 
TypeScript Best Practices
TypeScript Best PracticesTypeScript Best Practices
TypeScript Best Practices
felixbillon
 
⚛️ Reasonable React (with beers)
⚛️ Reasonable React (with beers)⚛️ Reasonable React (with beers)
⚛️ Reasonable React (with beers)
Thomas Haessle
 

Similar to Static types on javascript?! Type checking approaches to ensure healthy applications (20)

Clean & Typechecked JS
Clean & Typechecked JSClean & Typechecked JS
Clean & Typechecked JS
 
2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws
 
JavaScript for Web Analysts
JavaScript for Web AnalystsJavaScript for Web Analysts
JavaScript for Web Analysts
 
Functions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupFunctions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrup
 
C programming(part 3)
C programming(part 3)C programming(part 3)
C programming(part 3)
 
Stuff you didn't know about action script
Stuff you didn't know about action scriptStuff you didn't know about action script
Stuff you didn't know about action script
 
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
 
Ajax and JavaScript Bootcamp
Ajax and JavaScript BootcampAjax and JavaScript Bootcamp
Ajax and JavaScript Bootcamp
 
C++ boot camp part 1/2
C++ boot camp part 1/2C++ boot camp part 1/2
C++ boot camp part 1/2
 
C++ Boot Camp Part 1
C++ Boot Camp Part 1C++ Boot Camp Part 1
C++ Boot Camp Part 1
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
 
Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1
 
Kotlin
KotlinKotlin
Kotlin
 
Javascript status 2016
Javascript status 2016Javascript status 2016
Javascript status 2016
 
Programming with Java: the Basics
Programming with Java: the BasicsProgramming with Java: the Basics
Programming with Java: the Basics
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
 
Type script - advanced usage and practices
Type script  - advanced usage and practicesType script  - advanced usage and practices
Type script - advanced usage and practices
 
From android/java to swift (3)
From android/java to swift (3)From android/java to swift (3)
From android/java to swift (3)
 
TypeScript Best Practices
TypeScript Best PracticesTypeScript Best Practices
TypeScript Best Practices
 
⚛️ Reasonable React (with beers)
⚛️ Reasonable React (with beers)⚛️ Reasonable React (with beers)
⚛️ Reasonable React (with beers)
 

Recently uploaded

Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
kumardaparthi1024
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
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 | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
Neo4j
 
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
 
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
 
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
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Speck&Tech
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Safe Software
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
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
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
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
 
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
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
Pixlogix Infotech
 

Recently uploaded (20)

Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
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 | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
 
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
 
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
 
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
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
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
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
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
 
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
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
 

Static types on javascript?! Type checking approaches to ensure healthy applications

  • 1. Static Types on Javascript!? Type-checking approaches to ensure healthy applications (Tipos estáticos em Javascript?! Abordagens de type-checking para garantir uma aplicação saudável) Arthur Puthin
  • 2. About me Developer at ilegra (think beyond!) Mostly front-end stuff Undergraduate at Unisinos @aputhin @aputhin_
  • 4. So, what is this all about?
  • 5. - Types - JS Types - Why (or why not) Static Types - How to Static Types Agenda Actually, I just want to give you food for thought on Javascript typing, dynamic or static, and not champion any approach in particular
  • 7. Data types define, among other stuff: A set from which the data may take its' value The operations that can be performed on/with the data
  • 8. Values add, subtract, multiply, divide concat, substr and, or, xor, not Operations -∞ … -2, -1, 0, 1, 2, 3, 4 … +∞ abcdefghijklmnopqrstuvwxyz true, false
  • 9. Primitive types are basic data types which are usually built-in for each language Composite or complex types are derived from more than one primitive, and can be user-defined
  • 10. Programming languages' type systems may apply: Static type checking, which happens at compile time and validates variables' types Dynamic type checking, which happens at runtime and validates types for data itself
  • 11. Data Types: the JS Way
  • 12. In JavaScript, variables don't have types -- values have types. [...] Another way to think about JS types is that JS doesn't have "type enforcement" [...]. https://github.com/getify/You-Dont-Know-JS/blob/master/types%20%26%20grammar/ch1.md let a = 42; typeof a; // "number" a = true; typeof a; // "boolean"
  • 13. Primitives - null - undefined - boolean - number - string - symbol (ES2015) IMMUTABLE ASSIGN BY COPY let a = 41; let b = a; b++; console.log(a); // 41 console.log(b); // 42
  • 14. Object Type - objects of any shape - functions - arrays let a = [1, 2]; let b = a; b.push(3); console.log(a); // [1, 2, 3] console.log(b); // [1, 2, 3] b = [4, 5, 6]; console.log(a); // [1, 2, 3] console.log(b); // [4, 5, 6] MUTABLE ASSIGN BY REFERENCE let c = { isC: true }; let d = c; d.isC = false; console.log(c); // { isC: false } console.log(d); // { isC: false }
  • 15. Native Object Types - String() - Number() - Boolean() - Array() - Object() - Function() - RegExp() - Date() - Error() - ... const a = 'string'; const b = new String('string'); typeof a; // string typeof b; // object const c = a.split('', 3); // auto-boxing Primitive Wrappers
  • 16. Type coercion in Javascript can be: Implicit, when the runtime itself performs conversions, usually engaged to satisfy the surrounding context Explicit (a.k.a. type-casting), when the developer expresses the intention to convert between types by writing the appropriate code
  • 17. String conversion Boolean(2) // explicit if (2) { /**/ } // implicit !!2 // implicit 2 || 'hello' // implicit Boolean('') // false Boolean(0) // false Boolean(-0) // false Boolean(NaN) // false Boolean(null) // false Boolean(undefined) // false Boolean(false) // false // everything else is true! https://medium.freecodecamp.org/js-type-coercion-explained-27ba3d9a2839 Boolean conversion String(123) // explicit 123 + '' // implicit String(123) // '123' String(-12.3) // '-12.3' String(null) // 'null' String(undefined) // 'undefined' String(true) // 'true' String(false) // 'false'
  • 18. Number conversion https://medium.freecodecamp.org/js-type-coercion-explained-27ba3d9a2839 Number('123') // explicit +'123' // implicit (unary operator +) 123 != '456' // implicit (loose equality operator == !=) // except if both operands are strings! 4 > '5' // implicit (comparison operators > < <= >=) true | 0 // implicit (bitwise operators | & ^ ~) 5/null // implicit (arithmetic operators - + * / %) // except for + if either operand is a string!
  • 19. Object to Primitive Conversion 1. If input is already a primitive, do nothing and return it. 2. Call input.toString(), if the result is primitive, return it. 3. Call input.valueOf(), if the result is primitive, return it. 4. If neither input.toString() nor input.valueOf() yields primitive, throw TypeError. https://medium.freecodecamp.org/js-type-coercion-explained-27ba3d9a2839
  • 20. Be a responsible and mature developer. Learn how to use the power of coercion (both explicit and implicit) effectively and safely. And teach those around you to do the same. https://github.com/getify/You-Dont-Know-JS/blob/master/types%20%26%20grammar/ch4.md
  • 22. Why would we go static?
  • 23. "The most often-cited rationales for type systems are that they: 1. Catch errors early 2. Improve readability of code 3. Facilitate tooling 4. Improve runtime performance" http://www.hammerlab.org/2015/12/09/our-experiences-with-flow/
  • 24. ● It takes time to learn. ● It is an additional layer of complexity. ● It constrains your freedom of expression. ● It does not prevent defects. ● You lose some interactivity and compiling takes time. http://2ality.com/2018/03/javascript-typescript-reasonml.html
  • 27. 1. Supersets 2. Static Type Checkers 3. Compile-to-JS
  • 30. tsc webpack (ts-loader) babel (babel-preset-typescript) gulp (gulp-typescript) browserify (tsify)
  • 31. let isDone: boolean = false; let answer: number = 42; // includes hex, binary and octal let someValue: any = "this is a string"; let strLength: number = (<string>someValue).length; // type casting let anotherLength: number = (someValue as string).length; function warnUser(): void { // null or undefined alert("This is my warning message"); }
  • 32. let list1: number[] = [1, 2, 3]; let list2: Array<number> = [1, 2, 3]; let x: [string, number]; x = ["hello", 10]; // OK x = [10, "hello"]; // Error enum Color {Red, Green, Blue} let c: Color = Color.Green; // 2 let colorName: string = Color[2]; // Blue
  • 33. interface Record { readonly id: number; label: string; color?: string; // optional prop } class Greeter { private greeting: string; public constructor(message: string) { this.greeting = message; } } let greeter = new Greeter("world");
  • 34. // module exporting types and namespacing export namespace Validation { export interface StringValidator { isAcceptable(s: string): boolean; } } // checking normal js files with --checkJs flag /** @type {number} */ var x; x = false; // error
  • 35.
  • 37. // @flow const answer: number = 42; const indexes: Array<number> = [0, 1, 2]; // Array<T> let whatever: any; // wildcard whatever = 'string'; whatever = true; const func = (arg: number): number => {/*...*/}; // return type, optional
  • 38. // @flow const identity: { name: string, age: number } = { name: 'Jack', age: 15, }; type Address = { street: string, number: number }; type Email = string; // aliasing var message: ?string = null; // maybe: type, null or undef function setValue(value?: string) {/*...*/} // optional: type or undef
  • 39. // @flow type MyObject<A, B> = { foo: A, bar: B }; const val: MyObject<number, boolean> = { foo: 1, bar: true }; function getColor(name: "success" | "warning" | "danger") {/*...*/} type Foo = { foo: number }; type Bar = { bar: boolean }; let value: Foo & Bar = { foo: 1, bar: true };
  • 43. divide : Float -> Float -> Float divide x y = x / y type alias User = { name : String, bio : String, pic : String } hasBio : User -> Bool hasBio user = String.length user.bio > 0 -- alias auto-generates constructors for you :) User "Tom" "Friendly Carpenter" "http://example.com/tom.jpg"
  • 44. type Visibility = All | Active | Completed -- union type keep : Visibility -> List Task -> List Task keep visibility tasks = case visibility of -- has to cover all possibilities! All -> tasks Active -> List.filter (task -> not task.complete) tasks Completed -> List.filter (task -> task.complete) tasks
  • 45. toFullName person = person.firstName ++ " " ++ person.lastName fullName = toFullName { fistName = "Hermann", lastName = "Hesse" } The argument to function `toFullName` is causing a mismatch. 6│ toFullName { fistName = "Hermann", lastName = "Hesse" } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Function `toFullName` is expecting the argument to be: { …, firstName : … } But it is: { …, fistName : … } Hint: I compared the record fields and found some potential typos. firstName <-> fistName
  • 48. bsb
  • 49. let myInt = 5; /* inferred integer */ let myInt: int = 5; /* explicit definition */ let myInt = (5: int) + (4: int); /* definition mid-expression */ /* params and return types */ let add = (x: int, y: int) : int => x + y; let drawCircle = (~radius as r: int, ~color as c: string) => { setColor(c); startAt(r, r); /* ... */ };
  • 50. /* type aliases */ type scoreType = int; let x: scoreType = 10; /* parameterized type */ type coordinates('a) = ('a, 'a, 'a); type intCoordinatesAlias = coordinates(int); /* new type is created */ let buddy: intCoordinatesAlias = (10, 20, 20); /* new type is used */ let buddy: coordinates(float) = (10.5, 20.5, 20.5); /* inline flavor */ /* Mutually Recursive Types */ type student = {taughtBy: teacher} and teacher = {students: list(student)};
  • 52. Despite the tradeoffs that come with types like verbosity and the upfront investment to master them, the safety and correctness that types add to our programs make these “disadvantages” less of an issue for me personally. https://medium.freecodecamp.org/why-use-static-types-in-javascript-part-4-b2e1e06a67c9
  • 53. Static typing or not is an emotional topic. My advice is: ● Use whatever makes you happy and productive. ● Do acknowledge both strengths and weaknesses of what you are using. http://2ality.com/2018/03/javascript-typescript-reasonml.html
  • 54. Try stuff out, understand how each approach works and teach people around you!
  • 55. Thanks for your time! @aputhin @aputhin_