Typescript FTW

So... what is it

  • "TypeScript is a typed superset of JavaScript that compiles to plain JavaScript"
  • All the benefits of JavaScript with all the benefits of type safety and object oriented design
  • Open source project from Microsoft (shoutout to VS Code for excellent TS support and tooling)

Now how do we get started

  • npm install -g typescript
  • tsc helloworld.ts

interface?

    interface IHelloWorld {
	welcomeMessage: string;
	greet: (name: string) => string;
	updateWelcomeMessage(newMessage: string): void;
    }

    class HelloWorld implements IHelloWorld {
	public welcomeMessage: string;

	constructor() {
	    this.welcomeMessage = 'Hey, welcome to typescript 101';
	}

	public greet(name: string): string {
	    return `${this.welcomeMessage} ${name}`;
	}

	public updateWelcomeMessage(newMessage: string): void {
	    this.welcomeMessage = newMessage;
	}

    }

    export default HelloWorld

Types

  • Built ins: string, boolean, number, object, array, any
  • Use the | if you want the option for multiple types
  • You can make your own types (aka interfaces) that you can export and use throughout your repo
  • You can find publicly available types for lots of popular libraries
    • ie. npm i @types/react

Types cont.

  • Type inference
  • Namespaces can help to organize your custom types
  • Optional argument
    •  greet(message?: string)
  • Public
    • anyone can see me
  • Private
    • only viewable in this class
  • Protected
    • viewable in this class or classes that extend this class

Introducing access modifiers

Baby steps

  • TS can be introduced incrementally
  • Types are always optional
  • A repo can contain both .js and .ts
  • Declare things that do in fact exist
    • declare var $: any;

Why should you try TS

  • Flexibility of JavaScript with the structure of types
  • Refactoring is much easier
  • Catch errors before runtime
  • Easy for a new developer to jump on board and understand what's happening
  • Manageable incremental conversion from JS
  • Implicit typing means that typescript will do a lot of the heavy lifting before you even get started
  • Quick to embrace new ES features

Go forth and conquer

  • http://www.typescriptlang.org/play/
  • https://code.tutsplus.com/tutorials/typescript-for-beginners-getting-started--cms-29329

Typescript FTW

By borisonr

Typescript FTW

  • 691