YuWebdesign



Typescript Cheet Sheet

By YuwebDesign

Install and Compile Typescript

Install TypeScript
npm install -g typescript
  • Use command line to install TypeScript via npm (the Node.js package manager)
  • Visual Studio Code comes now with TypeScript by default.
  • Compile TypeScript
    tsc filename.ts Runs the TypeScript compiler at the command line.
    The result will be a file filename.js.

    When there are errors in filename.ts,
    the filename.js file will still be created.

    You can use TypeScript even if there are errors in your code.

    But in this case, TypeScript is warning that your code will likely not run as expected.

    TypeScript can offer static analysis based on both

    1. the structure of your code (e.g., function called with an expected number of parameters),
    2. and the type annotations you provide.

    Type annotations

    Type annotations in TypeScript
    are lightweight ways
    to record the intended contract
    of the function or variable.

    Command Description Example
    Boolean Simple true/false value,
    which JavaScript and TypeScript call a boolean value.
    let isDone: boolean = false;
    Number As in JavaScript, all numbers in TypeScript are floating point values.

    These floating point numbers get the type number.

    In addition to hexadecimal and decimal literals,
    TypeScript also supports binary and octal literals
    introduced in ECMAScript 2015.

    let decimal: number = 6;
    let hex: number = 0xf00d;
    let binary: number = 0b1010;
    let octal: number = 0o744;
    String Textual datatype.

    To surround string data, TypeScript uses

    1. double quotes (“)
    2. single quotes (‘)
    3. template strings,

      surrounded by the backtick/backquote (`) character,
      and embedded expressions are of the form ${ expr }

      can span multiple lines and have embedded expressions.

    let color: string = “blue”;
    color = ‘red';

    let fullName: string = `Elvis Presley`;
    let sentence: string = `Hello, my name is ${ fullName }.

    Array Array types can be written in one of two ways. In the first, you use the type of the elements followed by [] to denote an array of that element type let list: number[] = [1, 2, 3];
    The second way uses a generic array type, Array let list: Array = [1, 2, 3];
    Tuple Tuple types allow to express
    an array with a fixed number of elements
    whose types are not the same.
    // Declare a tuple type
    let x: [string, number];
    // Initialize it
    x = [“hello”, 10]; // OK
    // Initialize it incorrectly
    x = [10, “hello”]; // Error
    Enum Addition to the standard set of datatypes from JavaScript.

    Enum is a way of giving more friendly names to sets of numeric values.

    enum Color {Red, Green, Blue}
    let c: Color = Color.Green;
    By default, enums begin numbering their members starting at 0. You can change this by manually setting the value of one of its members. enum Color {Red = 1, Green, Blue} // start at 1
    let c: Color = Color.Green;
    Manually set all the values in the enum enum Color {Red = 1, Green = 2, Blue = 4}
    let c: Color = Color.Green;
    You can go from a numeric value
    to the name of that value in the enum.
    enum Color {Red = 1, Green, Blue}
    let colorName: string = Color[2];

    console.log(colorName); // Displays ‘Green’ as its value is 2 above

    Any Describe the type of variables that we do not know when we are writing an application.

    These values may come from dynamic content, e.g. from the user or a 3rd party library.

    In these cases, we want to opt-out of type checking and let the values pass through compile-time checks.

    Handy if you know only some part of the type, e.g. array with a mix of different type

    let notSure: any = 4;
    notSure = “maybe a string instead”;
    notSure = false; // okay, definitely a boolean

    let list: any[] = [1, true, “free”];

    Void opposite of any: the absence of having any type at all.

    Commonly the return type of functions that do not return a value.

    Declaring variables of type void is not useful because you can only assign

    1. null (only if –strictNullChecks is not specified)
    2. or undefined to them
    function warnUser(): void {
    console.log(“This is my warning message”);
    }
    Null and Undefined In TypeScript, both undefined and null
    actually have their own types
    named undefined and null respectively.

    Much like void, they’re not extremely useful on their own.

    By default null and undefined are subtypes of all other types.
    That means you can assign null and undefined to something like number.

    However, when using the –strictNullChecks flag,
    null and undefined are only assignable
    to any and their respective types
    (the one exception being that undefined is also assignable to void).

    This helps avoid many common errors.

    In cases where you want to pass in
    either a string or null or undefined,
    you can use the union type string | null | undefined.

    Never represents the type of values that never occur.

    1. E.g, the return type for a function expression
      or an arrow function expression
      that always throws an exception
      or one that never returns;
    2. Variables when narrowed by any type guards that can never be true.

    The never type is a subtype of, and assignable to, every type;
    however, no type is a subtype of, or assignable to, never (except never itself).

    Even any isn’t assignable to never.

    // Function returning never must have unreachable end point
    function error(message: string): never {
    throw new Error(message);
    }

    // Inferred return type is never
    function fail() {
    return error(“Something failed”);
    }

    // Function returning never must have unreachable end point
    function infiniteLoop(): never {
    while (true) {
    }
    }

    Object Object is a type that represents the non-primitive type,
    i.e. anything that is not

    1. number,
    2. string,
    3. boolean,
    4. bigint,
    5. symbol,
    6. null,
    7. or undefined
    declare function create(o: object | null): void;

    create({ prop: 0 }); // OK
    create(null); // OK

    create(42); // Error
    create(“string”); // Error
    create(false); // Error
    create(undefined); // Error

    Interfaces

    Command Description Example
    In TypeScript, two types are compatible
    if their internal structure is compatible.

    Interface is implemented
    without an explicit implements clause.

    The shape the interface requires is enough.

    interface Person {
    firstName: string;
    lastName: string;
    }

    let user = { firstName: “Jane”, lastName: “User” };

    Classes

    TypeScript supports class-based object-oriented programming.

    Classes and interfaces play well together,
    letting the programmer decide on the right level of abstraction.

    Command Description Example
    creates a Student class with a constructor and a few public fields.

    the use of public on arguments to the constructor
    is a shorthand that allows us to automatically create
    properties with that name.

    class Student {
    fullName: string;
    constructor(public firstName: string, public middleInitial: string, public lastName: string) {
    this.fullName = firstName + ” ” + middleInitial + ” ” + lastName;
    }
    }

    interface Person {
    firstName: string;
    lastName: string;
    }

    function greeter(person: Person) {
    return “Hello, ” + person.firstName + ” ” + person.lastName;
    }

    let user = new Student(“Jane”, “M.”, “User”);

    document.body.textContent = greeter(user);

    Leave a Reply or Comment

    Your email address will not be published. Required fields are marked *