Introduction to the

TypeScript is a superset of JavaScript that provides a type system and support for ES6. TypeScript is designed to build large applications that can be compiled into pure JavaScript and run in any browser.

TypeScript is a language extension that adds features to JavaScript. The added features include:

  • Type annotation and compile-time type checking
  • Type inference
  • Type erasure
  • interface
  • The enumeration
  • Mixin
  • Generic programming
  • Name space
  • tuples
  • Await

The installation

Install via NPM

npm install -g typescript
Copy the code

If the TSC -v version number is displayed, the installation is successful:

Ts as a TypeScript code file extension, TSC app.ts can compile TS code into JS.

TypeScript base types

Includes: any, number, string, Boolean, array, tuple, enum, void, null, never

  • Arbitrary type (any) : A data type used for variables whose type is not clear at programming time

  • The never type: Never is a subtype of other types, including null and undefined, and represents a value that never occurs. This means that a variable declared as type never can only be assigned by type never, and in functions it usually behaves as throwing an exception or failing to execute to a termination point (such as an infinite loop).

  • Enumeration (enum) : Enumeration types are used to define collections of values.

    enum Color {Red, Green, Blue};
    let c: Color = Color.Blue;
    console.log(c);    2 / / output
    Copy the code
  • Tuple: The tuple type is used to represent an array with the known number and type of elements. The types of the elements need not be the same.

    let x: [string, number];
    x = ['Runoob'.1];    // It is running properly
    x = [1.'Runoob'];    / / an error
    console.log(x[0]);    / / output Runoob
    Copy the code

TypeScript variable declarations

TypeScript variables are named as follows:

  • Variable names can contain both numbers and letters.
  • Cannot contain any special characters, including Spaces, except the underscore _ and dollar $.
  • Variable names cannot start with a number.

Var [variable name] : [type] = value;

TypeScript association types

Joint type (Union Types) can be set through the pipe (|) variable Types, assignment can be assigned according to the type of set.

Syntax format: Type1 | Type2 | Type3

    var val:string|number 
    val = 12 
    console.log("The number is"+ val) 
    val = "Runoob" 
    console.log("String as" + val)
Copy the code