📕
SEIRFX
  • Introduction
  • About These Notes
  • Schedule
  • Unit 2
    • Node
      • Internet Fundamentals
      • Full-Stack Fundamentals
      • Intro to Node
      • Node Modules
      • Node Packages
    • Express
      • Intro to Express
      • Routes
      • Routes Lab
      • Views
      • Templates
      • Layouts & Controllers
    • CRUD & REST
      • GET & POST
      • GET & POST Lab
      • PUT & DELETE
    • API Calls in Express
      • Axios
      • Request (no longer maintained)
    • Sequelize
      • Terminology
      • Setup
      • Using Models
      • Seeding Data
      • Validations and Migrations
      • Resources
      • 1:M Relationships
      • N:M Relationships
    • Express Authentication
      • Research Components
      • Code Components
      • Auth in Theory
        • Sessions
        • Passwords
        • Middleware
        • Hooks
      • Auth in Practice
        • Create the User
        • User Signup
        • Sessions
        • User Login
        • Authorization and Flash messages
  • Development Workflow
    • Command Line
      • The Terminal
      • Filesystem Navigation
      • File Manipulation
      • Additional Topics
    • Intro to Git
      • Version Control
      • Local Git
      • Remote Git
      • Git Recipes
    • Group Collaboration
      • Git Workflows
      • Project Roles and Tools
    • VS Code Tips & Tricks
  • HTML/CSS
    • HTML
    • CSS Selectors
    • CSS Box Model and Positioning
      • Box Model
      • Display and Positioning
      • Flexbox
      • Grid
      • Flexbox & Grid Games
      • Floats and Clears
      • Additional Topics
    • Advanced CSS
      • Responsive Design
      • Pseudo-Classes/Elements
      • Vendor Prefixes
      • Custom Properties
      • Additional Topics
    • Bootstrap
    • CSS Frameworks
    • Accessibility
  • JavaScript
    • Primitives
    • Arrays
    • Objects
      • Objects Lesson
      • Objects quick guide
      • Object-ception
    • Control Flow
      • Boolean Expressions
      • Conditionals
      • Loops
      • Promises
    • Functions
      • Scope
      • Callbacks
      • Higher Order Functions
      • Callbacks Review Lab
      • Timing Functions
      • Iterators
      • Combining Data Types
      • Combining Data Types Lab
    • Javascript in the browser
      • DOM and Events
      • DOM Manipulation
      • DOM Review
      • DOM Review Lab
      • HP DOM Lab
      • Programmatic DOM Manipulation
      • Grids & Pyramids
      • DOM & Data
      • DOM Events
      • Color Palette Picker
      • Sketchpad
    • HTML5 Canvas
    • How To Reduce Redundancy
    • OOP
      • Westworld Lab
      • OOP Factories
      • OOP Inheritance
      • OOP Inheritance Lab
      • Tomagotchi Lab
      • OOP Space Battle
      • OOP Snowman
      • (2019) JavaScript OOP
      • (2016) OOP with Classes
      • (1995) OOP with Prototypes
      • Constructors
      • Prototypes
    • Intro to TDD
    • Scoping
    • Inheritance
      • Prototypal Inheritance
      • Call, Apply, and other Functions
      • ES6 Inheritance
      • Resources
    • Custom Node Modules
    • Additional Topics
      • AJAX, Fetch, and Async/Await
      • AJAX w/JSON and Localstorage
        • AJAX w/JSON
        • Local Storage
      • Async module
      • Data Scraping
  • jQuery
    • Intro
      • DOM Manipulation
      • Reddit Practice
      • Styling
      • Events
    • Plugins
    • AJAX
  • APIs
    • Fetch
    • AJAX w/jQuery
    • AJAX w/Fetch
  • Databases
    • Intro to SQL
    • Advanced SQL
    • MongoDB
      • Intro to NoSQL
      • CRUD in MongoDB
      • Data Modeling
      • Intermediate Mongo
  • Left over Node/Express
    • Testing with Mocha and Chai
    • Mongoose
      • Mongoose Associations
    • JSON Web Tokens
      • Codealong
    • Additional Topics
      • oAuth
      • Geocoding with Mapbox
      • Geocoding and Google Maps
      • Cloudinary
      • Websockets with Socket.io
      • SASS
  • Ruby
    • Intro to Ruby
    • Ruby Exercises
    • Ruby Classes
    • Ruby Testing with Rspec
    • Ruby Inheritance
    • Ruby Data Scraping
  • Ruby on Rails
    • Intro to Rails
    • APIs with Rails
    • Asset Pipeline
    • Rails Auth and 1-M
      • Auth Components
    • Rails N:M
    • ActiveRecord Polymorphism
    • Additional Topics
      • oAuth
      • SASS
      • Rails Mailers
      • Cloudinary
      • Jekyll
  • React (Updated 2019)
    • ES6+/ESNext
      • Const and Let
      • Arrow Functions
      • Object Literals and String Interpolation
      • ES6 Recap
      • ES6 Activity
    • Intro to React
      • Create React App
      • Components and JSX
      • Virtual DOM
      • Props
      • Dino Blog Activity
      • Nested Components
      • Lab: LotR
    • React State
      • Code-Along: Edit Dino Blog
      • Lab: Simple Calc
      • Lifting State
    • React Router
      • Browser History/SPAs
      • React Router (lesson and full codealong)
      • Router Lab
    • Fetch and APIs
      • APIs with Fetch and Axios
      • Fetch the Weather
    • React Hooks
    • React LifeCycle
      • Lab: Component LifeCycle
    • React Deployment
    • Additional Topics
      • React Frameworks
        • Material UI Theming
      • Typescript
        • More Types and Syntax
        • Tsconfig and Declaration Files
        • Generics with Linked List
      • Redux
      • TypeScript
      • Context API
      • React Native
  • Meteor
  • Deployment and Config
    • Installfest
      • Mac OSX
      • Linux
      • Git Configuration
      • Sublime Packages
    • Deploy - Github Pages
    • Deploy - Node/Sequelize
    • Deploy - Node/MongoDB
    • Deploy React
    • Deploy - Rails
      • Foreman (Environment Variables)
    • Deploy - AWS Elastic Beanstalk
    • Deploy - S3 Static Sites
    • Deploy - Django
    • Deploy - Flask
  • Data Structures and Algorithms
    • Recursion
    • Problem Solving - Array Flatten
    • Binary Search
    • Algorithm Complexity
    • Stacks and Queues
    • Bracket Matching
    • Ruby Linked Lists
      • Sample Code
      • Beginner Exercises
      • Advanced Exercises
    • JS Linked Lists
      • Sample Code
      • Beginner Exercises
      • Beginner Solutions
    • Hash Tables
    • Intro to Sorting
    • Insertion Sort
    • Bucket Sort
    • Bubble Sort
    • Merge Sort
    • Quick Sort
    • Heap Sort
    • Sorting Wrapup
    • Hashmaps
    • Trees and Other Topics
  • Python
    • Python Installation
    • Intro to Python
    • Python Lists
    • Python Loops
    • Python Dictionaries
    • Python Sets and Tuples
    • Python Cheatsheet
    • Python Functions
    • Python Classes
    • Python Class Inheritance
    • Intro to Flask
    • Intro to SQLAlchemy
      • Flask and SQLAlchemy
    • Using PyMongo
    • Intro to Django
    • CatCollector CodeAlong
      • URLs, Views, Templates
      • Models, Migrations
      • Model Form CRUD
      • One-to-Many Relations
      • Many-to-Many Relations
      • Django Auth
    • Django Cheatsheet
    • Django Auth
    • Django Polls App Tutorial
    • Django School Tool Tutorial
    • Django 1:M Relationships
    • Custom Admin Views
    • Data Structures and Algorithms
      • Recursion
      • Binary Search
      • Stacks and Queues
      • Linked Lists
      • Binary Trees
      • Bubble Sort
      • TensorFlow & Neural Networks
    • Adjacent Topics
      • Raspberry Pi
      • Scripting
  • Assorted Topics
    • History of Computer Science
    • Regular Expressions
    • Being Successful in SEI
    • Internet Fundamentals
      • Internet Lab
    • Adjacent Workflow
      • UX/UI
      • Wireframing Exercise: Build an Idea
      • Agile
    • Post SEI
      • Learning Resources
      • Deliverables -> Portfolio
      • FAQ
  • Projects
    • Project 1
    • Project 2
    • Project 3
      • Project 3 Pitch Guidelines
    • Project 4
    • Past Projects
      • Project 1
      • Project 2
      • Project 3
      • Project 4
      • Portfolios
    • Post Project 2
    • MEAN Hackathon
      • Part 1: APIs
      • Part 2: Angular
    • Portfolio
  • Web Development Trends
  • Resources
    • APIs and Data
    • Tech Websites
    • PostgreSQL Cheat Sheet
    • Sequelize Cheat Sheet
    • Database Administration
  • Archived Section
    • (Archived) ReactJS
      • Intro to React
        • Todo List Codealong
        • Additional Topics
      • Deploy React
      • React with Gulp and Browserify
        • Setting up Gulp
        • Additional Gulp Tasks
      • React Router
        • OMDB Router
        • OMDB Search
        • Additional Resources
      • React Animations
        • CSS Animations
    • AngularJS
      • Intro to AngularJS
        • Components and SPA
        • Create an Angular App
      • Angular Directives and Filters
      • Angular Animation
      • Angular Bootstrap Directives
        • Bootstrap Modals
      • Angular $http
      • Angular Services
        • Service Recipes
        • ngResource
        • Star Wars Codealong
      • Angular Routing
      • Angular + Express
      • Angular Authentication
        • Additional Topics
      • Angular Components
      • Angular Custom Filters
      • Angular Custom Directives
Powered by GitBook
On this page
  • TypeScript
  • Why TypeScript?
  • Disadvantages
  • Let's get started!
  • Basic Types
  • Applying Type constraints to variables
  • Typing Functions

Was this helpful?

  1. React (Updated 2019)
  2. Additional Topics

Typescript

PreviousMaterial UI ThemingNextMore Types and Syntax

Last updated 4 years ago

Was this helpful?

TypeScript

Learning Objectives

  • Describe advantages and disadvantages to using TypeScript

  • Identify and use basic types, interfaces and additional TypeScript stuff

  • Understand type inference and declaration

  • Configure and use the typescript compiler

Why TypeScript?

  • Identifying bugs at compile time is better than finding them at runtime

  • Type enforcement in large code bases reduces bugs across the organization/teams/time

  • TypeScript allows ESNext syntax -- though many of the features highlighted by TS folks have been introduced with ES6 and 7

  • Lowish barrier to entry

    • can use it sparingly to start (your JS is probably fine, just add some typings or any)

    • implicit and explicit typing

This is a pretty great resource put together by some benevolent dev:

Disadvantages

  • Adds complexity to your project

    • directory structure needs source and build

    • setup compiler or babel and/or webpack and build step

  • TS compiler will yell at you for things that you have perceived as legal for the entirety of your JS career

  • Advanced techniques can be a little confusing

Let's get started!

Install TypeScript and its compiler on your local machine!

$ npm install -g typescript
$ tsc -v 
Version 3.3.X

We're all set!

Let's test it out

$ mkdir ts_sandbox && cd ts_sandbox
$ touch type_fun.ts

type_fun.ts

let hello: string = "Hello, World!"

Save your type_fun.ts and run this bash command:

$ tsc type_fun.ts
$ ls

You should now see two files, type_fun.ts and type_fun.js! The tsc command compiles our typescript file into javascript!

$ cat type_fun.js

var hello = "Hello, World!"

Basic Types

We can get started with TypeScript by adding just a little extra cruft to the JS syntax we know and love. By now, you are all very familiar with the javascript primitives: string, number, boolean. TypeScript makes use of these primitives... and then adds to it!

Applying Type constraints to variables

In order to apply type constraints to our variables with TypeScript, all we need to do is declare a type after the variable name, separated by a colon

let myVariable: type = "my value"

Basic Types

<= according to the TS Docs 🎉

String

Your run of the mill string type

Number

Can be used with decimal integers and floats as well as hex, octal and binary numbers

Boolean

our old friends true and false

Any

oh my! you're telling me I don't actually have to plan ahead?

Array

lets add primitive typings to arrays (syntax may vary!)

void

used for functions that do not return a value

null

null, this is one of Typescript's two subtypes

undefined

undefined, Typescript's other subtype

Object

anything that is not number, string, boolean, null, or undefined

never

represents the type of values that never occur

Tuple

enforced typings on a specified number elements

Enum

Enforce a set of values -- we can use custom Types in many cases

string

let myString: string = "Hello, World!"
let myTemplateLiteral: string = `"${myString}" is the phrase we always use when learning a new language.`

number

let myInt: number = 3;
let myFloat: number = 6.4;
let myHex: number = 0xf00d;
let myOct: number = 0o744;
let myBin: number = 0b1010;

boolean

let myBool: boolean = true;
myBool = false;

any

When a data type is not known or required ahead of time, any can be used.

let myAny: any = 'what should we throw in here?'
myAny = 7
myAny = true

// all ok!

However, if we know that a variable can accept both strings or numbers, TypeScript allows us to plan for this scenario with the | operator. (This is called a "Union" type and can be a more advanced technique)

let myIndecisiveVar: string | number = 'This is ok!'
myIndecisiveVar = 5 // also ok!
myIndecisiveVar = false // Throws an error

The Subtypes

Typescript gives us two subtypes, null and undefined. These are used when we've defined the type of a variable, but we don't know what that value is yet.

let futureVar: number = undefined
// OR
let futureVar: number = null
// may require use of the `as` keyword
let futureVar = null as number;

Arrays

TypeScript offers 2 options for enforcing type constraints on an array. 1. Adding [] after a type declaration 2. Using angle brackets and the Array generic type

let myStrings: string[] = ['Hello','World'];
let myStringArray: Array<string> = ['Hello','Squirrel'];

let myNums: number[] = [9,3,6,12];
let myNumArr: Array<number> = [3,3,3,3,3,3];

let arrayOfAny: any[] = ['what','is','purpose','of','this','array','?!', 2, true, {gross: "yup"}]

Be careful when using the angle bracket notation as it can cause conflicts when working with TSX, the TypeScript equivalent of JSX.

Typing Functions

The format we used to add type constraints to our functions and methods is as follows:

// function identifier(arg: type): returnType {}
function myFunc(arg: string, arg2: number): string {
    // myFunc logic
    return 'The string';
}

const myArrowFunc = (arg:string, arg2: number): string[] => {
    // logic
    return ['','',''];
}

If our function will not be returning anything, we can assign the return type void.

function myVoidFunc(data: string[]): void {
    data.forEach( (datum: string): void => {
        console.log(datum)
    })
}

Explicit vs Implicit Typing

All this extra syntax making your headspin?

The typescript compiler can infer some of your typings from the initial definition!

let str: string = 'I am explicitly defined as a string type'
let otherStr = 'I am implicitly defined as a string type'

function printMsg(message: string): void {
    console.log(message)
}

printMsg(str) // Works!
printMsg(otherStr) // Also Works!

In essence, typescript looks at a variable that isn't typed (in this case otherStr) and says, "This looks like a string, follows the sytax of a string, must be a string!"

This will be more apparent and relevant when we get into interfaces and enforcing object type structures in the next section.

The rules that govern these type inferences can vary and/or be configured by the compiler. In general, if the data type is not primitive, it is unlikely that implicit typping will work.

Must be gelfling

For more information:

TypeScript Deep Dive by @basarat
Rules of Type Inference
TypeScript Docs / Handbook