SlideShare a Scribd company logo
Type Checking JavaScript
Pascal-Louis Perez (pascal@kaching.com) - Closure Compiler
What is Type Checking?

• A particular kind of code analysis


• Looks at the flow of values


• Groups values as types


• Abstract interpretation to propagate types


• Can be dynamic or static
Dynamic Type Checking

Java
Object[] objects = new Integer[1];
objects[0] = new Double(4.3);

Object o = new Integer(6);
Date d = (Date) o;

JavaScript
new 3

null.getName();
Static Type Checking


 3        7


  a + b




     10
Static Type Checking


 3        7   ‘a’   7


  a + b        a + b




     10        ‘a7’
Static Type Checking


 3        7   ‘a’   7   3   null


  a + b        a + b    a + b




     10        ‘a7’         3
Static Type Checking


 3        7   ‘a’   7   3   null ‘3’ null


  a + b        a + b    a + b     a + b




     10        ‘a7’         3    ‘3null’
Static Type Checking


 3        7   ‘a’   7   3   null ‘3’ null


  a + b        a + b    a + b     a + b     ...

     10        ‘a7’         3    ‘3null’
Static Type Checking


 3        7   ‘a’   7   3   null ‘3’ null         number   number


  a + b        a + b    a + b     a + b     ...        a + b




     10        ‘a7’         3    ‘3null’             number
Motivating Example: Correctness

function(opt_i) {
  /** @type number */
  var index = opt_i === null ? 0 : opt_i;
  ...
}

• Meaningless or useless operations (such as null == null, undefined.foo)


• Wrong number of arguments for methods


• ...
Motivating Example: Optimizations

• Function Inlining


• Dead Code


• Constant Folding



...
Foo.prototype.get() = function() { return 5 }
Bar.prototype.get() = function() { return 2 }
...
v.get();
JavaScript Types


                         null



                         boolean
       number

                                      Object


                string




                          undefined
JavaScript Types


                         null
                                      Error


                         boolean
       number

                                          Object


                string




                          undefined
JavaScript Types


                         null
                                      Error

                                      SyntaxError
                         boolean
       number

                                          Object


                string




                          undefined
JavaScript Types


                          null
                                       Error

                                       SyntaxError
                          boolean
        number

                                           Object


                 string



      (boolean,string)
                           undefined
Optionality and Nullability

• JavaScript has two unit types null and undefined


• Thanks to union types, we can make the type system understand optionality
  and nullability


• Optionality: optional type T = (T, undefined)


• Nullability: nullable type T = (T, null)
Closure Compiler assumptions

• Functions and methods are not changed at runtime


• Protoypes are not changed at runtime, i.e. the type hierarchy is fixed


• Functions are called statically or not (but not both)

• eval   is used in a non disruptive way


• no use of with
Closure Compiler assumptions

• Functions and methods are not changed at runtime


• Protoypes are not changed at runtime, i.e. the type hierarchy is fixed


• Functions are called statically or not (but not both)

• eval   is used in a non disruptive way


• no use of with
                                       clean programming
Variables



/** @type number */
var n = 4;

/** @type {Array.<string>} */
var a = [‘hello’, ‘Zurich’];
Properties



/** ... */
function Foo() {
  /** @type {string?}
  this.bar = null;
}

/** @type {boolean|undefined} */
Foo.prototype.default = true;
Enums

/** @enum */
var options = {
  GOOD: 0, BAD: 1
}

/** @enum {string} */
var airports = {
  SFO: ‘San Francisco’, ...
}

/** @type {airports} */
var local = airports.SFO;
Functions



/**
  * @param {String} s
  * @return string
  */
function cast(s) {
   return String(s);
}
Constructors


/**
  * ...
  * @constructor
  */
function MyObject(...) {
   ...
}

new MyObject();
This


/**
  * @this Foo
  */
function handler(...) {
   ...
   this.bar
   ...
}
Type Refinement

• Unlike other language, the type of a variable depends on the program point



     /** @type {string?} */
     var s = ...;
     if (s) {
       ...
     } else {
       ...
     }
Type Refinement

• Unlike other language, the type of a variable depends on the program point



     /** @type {string?} */
     var s = ...;
     if (s) {
       ...                                   s : string
     } else {
       ...
     }
Type Refinement

• Unlike other language, the type of a variable depends on the program point



     /** @type {string?} */
     var s = ...;
     if (s) {
       ...                                   s : string
     } else {
       ...                                   s : (sting,null)
     }
Type Refinement

• Semantic based

  • variable == null, variable === undefined, variable < 7,   etc.


• Pattern based

  • goog.isDef(variable), goog.isNull(variable),
    goog.isDefAndNotNull(variable)
Type Inference

• Find the type of an expression without requiring any annotation



 var goog = {};

 goog.FOO = 5;

 /** @type number */
 goog.BAR = goog.FOO + 12;

More Related Content

PPS
Master in javascript
PPT
The JavaScript Programming Language
PPT
JavaScript: The Language
PPTX
Types, classes and concepts
PDF
Cat's anatomy
PDF
Back to the Future with TypeScript
PDF
Gunosy.go#7 reflect
Master in javascript
The JavaScript Programming Language
JavaScript: The Language
Types, classes and concepts
Cat's anatomy
Back to the Future with TypeScript
Gunosy.go#7 reflect

What's hot (20)

PDF
Compiler Construction | Lecture 7 | Type Checking
PDF
Objective-C to Swift - Swift Cloud Workshop 3
PPTX
2.dynamic
PPTX
Storage class in c
PPT
Generic Types in Java (for ArtClub @ArtBrains Software)
PPTX
Storage classes in C
PPT
Storage classes
PPTX
Developer’s viewpoint on swift programming language
PPTX
Storage classes in C
PDF
Some basic FP concepts
PPTX
Storage Class in C Progrmming
PDF
Dynamic Type Inference for Gradual Hindley–Milner Typing
PPTX
11 lec 11 storage class
PDF
Pd Kai#2 Object Model
PDF
Under the hood of scala implicits (Scala eXchange 2014)
PDF
JavaScript For CSharp Developer
PPT
Elements of functional programming
PPT
Introductory func prog
PPT
Introduction Functional Programming - Tech Hangout #11 - 2013.01.16
PDF
Working with Cocoa and Objective-C
Compiler Construction | Lecture 7 | Type Checking
Objective-C to Swift - Swift Cloud Workshop 3
2.dynamic
Storage class in c
Generic Types in Java (for ArtClub @ArtBrains Software)
Storage classes in C
Storage classes
Developer’s viewpoint on swift programming language
Storage classes in C
Some basic FP concepts
Storage Class in C Progrmming
Dynamic Type Inference for Gradual Hindley–Milner Typing
11 lec 11 storage class
Pd Kai#2 Object Model
Under the hood of scala implicits (Scala eXchange 2014)
JavaScript For CSharp Developer
Elements of functional programming
Introductory func prog
Introduction Functional Programming - Tech Hangout #11 - 2013.01.16
Working with Cocoa and Objective-C
Ad

Similar to Type Checking JavaScript (20)

PPT
Intermediate JavaScript
PPT
Javascript
PPTX
Things that every JavaScript developer should know by Rachel Appel at FrontCo...
PPTX
Interesting Facts About Javascript
KEY
第7回みゆっき☆Think 本気で学ぶ JavaScript
KEY
みゆっき☆Think#7 「本気で学ぶJavascript」
PPTX
Complete Notes on Angular 2 and TypeScript
PDF
TYPESCRIPT.pdfgshshhsjajajsjsjjsjajajjajjj
PPTX
Front end fundamentals session 1: javascript core
PPTX
About Python
PPT
introduction to javascript concepts .ppt
PDF
ECMA 入门
PPT
Primitive Data Types and Variables Lesson 02
PPT
fundamentals of JavaScript for students.ppt
PPT
Basics of Javascript
PDF
Java Script Workshop
PPTX
App_development55555555555555555555.pptx
PDF
JavaScript Basics and Best Practices - CC FE & UX
PDF
JavaScript Programming
PDF
JavaScript: Patterns, Part 2
Intermediate JavaScript
Javascript
Things that every JavaScript developer should know by Rachel Appel at FrontCo...
Interesting Facts About Javascript
第7回みゆっき☆Think 本気で学ぶ JavaScript
みゆっき☆Think#7 「本気で学ぶJavascript」
Complete Notes on Angular 2 and TypeScript
TYPESCRIPT.pdfgshshhsjajajsjsjjsjajajjajjj
Front end fundamentals session 1: javascript core
About Python
introduction to javascript concepts .ppt
ECMA 入门
Primitive Data Types and Variables Lesson 02
fundamentals of JavaScript for students.ppt
Basics of Javascript
Java Script Workshop
App_development55555555555555555555.pptx
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Programming
JavaScript: Patterns, Part 2
Ad

More from Pascal-Louis Perez (14)

PDF
Fuchsia RFCs
PDF
Products’ Love Story with Biz
PDF
How to Send a Receipt, Topics in Concurrency and Distributed Systems
PDF
Corporate Finance Primer
PDF
Developing an Immune System — The Hard and Soft Skills required to avoid Outages
PPTX
SLL Conf - Continuous Deployment
PDF
Alchemist Startup Primer - Lean Development Practices
PPTX
Database compatibility
PPTX
Applying Compiler Techniques to Iterate At Blazing Speed
PPTX
Iterate Like a Whirling Dervish
PDF
Extreme Testing at kaChing
PPT
Xignite's Dedicate kaChing Api
PPT
Add (Syntactic) Sugar To Your Java
PPT
kaChing's API garage event
Fuchsia RFCs
Products’ Love Story with Biz
How to Send a Receipt, Topics in Concurrency and Distributed Systems
Corporate Finance Primer
Developing an Immune System — The Hard and Soft Skills required to avoid Outages
SLL Conf - Continuous Deployment
Alchemist Startup Primer - Lean Development Practices
Database compatibility
Applying Compiler Techniques to Iterate At Blazing Speed
Iterate Like a Whirling Dervish
Extreme Testing at kaChing
Xignite's Dedicate kaChing Api
Add (Syntactic) Sugar To Your Java
kaChing's API garage event

Recently uploaded (20)

PDF
Machine learning based COVID-19 study performance prediction
PPTX
Spectroscopy.pptx food analysis technology
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
Cloud computing and distributed systems.
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Electronic commerce courselecture one. Pdf
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPT
Teaching material agriculture food technology
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Encapsulation theory and applications.pdf
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Machine learning based COVID-19 study performance prediction
Spectroscopy.pptx food analysis technology
Diabetes mellitus diagnosis method based random forest with bat algorithm
The Rise and Fall of 3GPP – Time for a Sabbatical?
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
MYSQL Presentation for SQL database connectivity
Cloud computing and distributed systems.
MIND Revenue Release Quarter 2 2025 Press Release
Encapsulation_ Review paper, used for researhc scholars
Electronic commerce courselecture one. Pdf
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Teaching material agriculture food technology
Review of recent advances in non-invasive hemoglobin estimation
Building Integrated photovoltaic BIPV_UPV.pdf
Advanced methodologies resolving dimensionality complications for autism neur...
Encapsulation theory and applications.pdf
Programs and apps: productivity, graphics, security and other tools
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf

Type Checking JavaScript

  • 2. What is Type Checking? • A particular kind of code analysis • Looks at the flow of values • Groups values as types • Abstract interpretation to propagate types • Can be dynamic or static
  • 3. Dynamic Type Checking Java Object[] objects = new Integer[1]; objects[0] = new Double(4.3); Object o = new Integer(6); Date d = (Date) o; JavaScript new 3 null.getName();
  • 4. Static Type Checking 3 7 a + b 10
  • 5. Static Type Checking 3 7 ‘a’ 7 a + b a + b 10 ‘a7’
  • 6. Static Type Checking 3 7 ‘a’ 7 3 null a + b a + b a + b 10 ‘a7’ 3
  • 7. Static Type Checking 3 7 ‘a’ 7 3 null ‘3’ null a + b a + b a + b a + b 10 ‘a7’ 3 ‘3null’
  • 8. Static Type Checking 3 7 ‘a’ 7 3 null ‘3’ null a + b a + b a + b a + b ... 10 ‘a7’ 3 ‘3null’
  • 9. Static Type Checking 3 7 ‘a’ 7 3 null ‘3’ null number number a + b a + b a + b a + b ... a + b 10 ‘a7’ 3 ‘3null’ number
  • 10. Motivating Example: Correctness function(opt_i) { /** @type number */ var index = opt_i === null ? 0 : opt_i; ... } • Meaningless or useless operations (such as null == null, undefined.foo) • Wrong number of arguments for methods • ...
  • 11. Motivating Example: Optimizations • Function Inlining • Dead Code • Constant Folding ... Foo.prototype.get() = function() { return 5 } Bar.prototype.get() = function() { return 2 } ... v.get();
  • 12. JavaScript Types null boolean number Object string undefined
  • 13. JavaScript Types null Error boolean number Object string undefined
  • 14. JavaScript Types null Error SyntaxError boolean number Object string undefined
  • 15. JavaScript Types null Error SyntaxError boolean number Object string (boolean,string) undefined
  • 16. Optionality and Nullability • JavaScript has two unit types null and undefined • Thanks to union types, we can make the type system understand optionality and nullability • Optionality: optional type T = (T, undefined) • Nullability: nullable type T = (T, null)
  • 17. Closure Compiler assumptions • Functions and methods are not changed at runtime • Protoypes are not changed at runtime, i.e. the type hierarchy is fixed • Functions are called statically or not (but not both) • eval is used in a non disruptive way • no use of with
  • 18. Closure Compiler assumptions • Functions and methods are not changed at runtime • Protoypes are not changed at runtime, i.e. the type hierarchy is fixed • Functions are called statically or not (but not both) • eval is used in a non disruptive way • no use of with clean programming
  • 19. Variables /** @type number */ var n = 4; /** @type {Array.<string>} */ var a = [‘hello’, ‘Zurich’];
  • 20. Properties /** ... */ function Foo() { /** @type {string?} this.bar = null; } /** @type {boolean|undefined} */ Foo.prototype.default = true;
  • 21. Enums /** @enum */ var options = { GOOD: 0, BAD: 1 } /** @enum {string} */ var airports = { SFO: ‘San Francisco’, ... } /** @type {airports} */ var local = airports.SFO;
  • 22. Functions /** * @param {String} s * @return string */ function cast(s) { return String(s); }
  • 23. Constructors /** * ... * @constructor */ function MyObject(...) { ... } new MyObject();
  • 24. This /** * @this Foo */ function handler(...) { ... this.bar ... }
  • 25. Type Refinement • Unlike other language, the type of a variable depends on the program point /** @type {string?} */ var s = ...; if (s) { ... } else { ... }
  • 26. Type Refinement • Unlike other language, the type of a variable depends on the program point /** @type {string?} */ var s = ...; if (s) { ... s : string } else { ... }
  • 27. Type Refinement • Unlike other language, the type of a variable depends on the program point /** @type {string?} */ var s = ...; if (s) { ... s : string } else { ... s : (sting,null) }
  • 28. Type Refinement • Semantic based • variable == null, variable === undefined, variable < 7, etc. • Pattern based • goog.isDef(variable), goog.isNull(variable), goog.isDefAndNotNull(variable)
  • 29. Type Inference • Find the type of an expression without requiring any annotation var goog = {}; goog.FOO = 5; /** @type number */ goog.BAR = goog.FOO + 12;