What is TypeScript

Before we get into TypeScript (ts), let’s talk about a few concepts: weak versus strong typing (from a type-safety perspective); Static versus dynamic typing (type checking perspective).

  • Weak type: tends not to tolerate implicit type conversions.
  • Strong typing: Prefers not to tolerate implicit type conversions.
  • Dynamic typing: a language that does data type checking only at run time. Instead of assigning a data type to a variable when programming in a dynamic language, the language records the data type internally the first time you assign a value to a variable.
  • Statically typed: In contrast to dynamically typed languages, datatype checking occurs at compile time, which means that variables are declared at program writing time.

We know that JS is a weakly typed and dynamically typed language, which makes us more flexible when programming, but also brings many new problems. Let’s look at a piece of code:

// A problem with JavaScript weak typing

// 1. Exceptions cannot be found until runtime
const obj = {}
 obj.foo()
setTimeout(() = > {
    obj.foo()
}, 1000000)

// 2. The function function may change
function sum(a, b) {
    return a + b
}
console.log(sum(100.100))
console.log(sum(100.'100'))

// 3. Incorrect use of the object indexer
const obj = {}
obj[true] = 100 // Attribute names are automatically converted to strings
console.log(obj['true'])

Copy the code

That’s why WE have TS in JS, which is a superset of JavaScript and essentially adds optional static typing and class-based object-oriented programming to the language.

Install and use TypeScript

1. Install the TypeScript

$ npm install -g typescript
Copy the code

2. Compile TypeScript files

$ tsc helloworld.ts
# helloworld.ts => helloworld.js
Copy the code

TypeScript base types

1. The Boolean type

 let isDone: boolean = false;
// ES5: var isDone = false;
Copy the code

2. The Number type

let count: number = 10;
Var count = 1;
Copy the code

3. Type String

let str: string = 'hello';
// ES5: var STR = 'hello';
Copy the code

4. Null and Undefined

let u: undefined = undefined;
let n: null = null;
Copy the code

5. The Symbol type

const h: symbol = Symbol(a);Copy the code

6. An Array type

let list: number[] = [1.2.3];
Var list = [1,2,3];

let list: Array<number> = [1.2.3]; // Array
      
        generic syntax
      
Var list = [1,2,3];
Copy the code

7. Enum type

/ / the enumeration

const enum postStatus {
  benagin,
  start,
  fineshed
}

const obj ={
  a:1.b:postStatus.benagin
}
console.log(obj)
Copy the code

8. The Tuple type

// Tuple
const tuple: [number, string] = [18.'zce']


const entries: [string, number][] = Object.entries({
  foo: 123.bar: 456
})
const [key, value] = entries[0]
// key => foo, value => 123
Copy the code

9. The Void type

const e: void = undefined
const e1: void = null

// Declare the function to return void
function warnUser() :void {
  console.log("This is my warning message");
}
Copy the code

10. Any type

let notSure: any = Awesome!;
notSure = "Semlinker";
notSure = false;
Copy the code

TypeScript assertions

Sometimes you’ll find that you know more about a value than TypeScript does. Usually this happens when you clearly know that an entity has a more exact type than its existing type.

Type assertions are a way of telling the compiler, “Trust me, I know what I’m doing.” Type assertion is like conversion in other languages, but without special data checking and deconstruction. It has no run-time impact, only at compile time.

Type assertions come in two forms:

  1. Angle bracket syntax
let arr:number[] = [1.2.3.4]
let num = arr.find(i= >i>1)
let add =  <number>num  +  <number>num // React cannot be used under JSX
Copy the code
  1. As grammar
let arr:number[] = [1.2.3.4]
let num = arr.find(i= >i>1)
let add =( num as number)  + ( num as number)// It is recommended to write this
Copy the code

Union types and type aliases

  1. The joint type
const sayHello = (name: string | undefined) = > {
  / *... * /
};
Copy the code
  1. Type the alias
type Message = string | string[];

let greet = (message: Message) = > {
  // ...
};
Copy the code

TypeScript interfaces

An interface is an important concept in object-oriented languages. It is an abstraction of behavior that needs to be implemented by classes.

Interfaces in TypeScript are a very flexible concept. In addition to abstracting some of the behavior of a class, interfaces are often used to describe the Shape of an object.

interface Post {
  title: string
  content: string
}

function printPost (post: Post) {
  console.log(post.title)
  console.log(post.content)
}
Copy the code

TypeScript generics

Generics is a template that allows the same function to take different types of arguments. It is better to create reusable components using generics than using any type because they preserve parameter types.

//// generics greatly improve code reuse
function fn1<T> (len:number,value:T) :T[]{
  return Array<T>(len).fill(value)
 }
fn1(4.5)

fn1(4.'4')
Copy the code

Eight, TypeScript

1. Class attributes and methods

// Class (Class)

export {} // Make sure there are no member conflicts with other examples

class Person {
  
  Class attributes must be specified in the type before being used
  name: string // = 'init name'
  age: number
  private sex: string // Private member, accessible only in the current class
  protected readonly gender: boolean // Protect members can be accessed in subclasses
  
  constructor (name: string, age: number,sex: string,gender: boolean,) {
    this.name = name
    this.age = age
    this.sex = sex
    this.gender = gender
  }

  sayHi (msg: string): void {
    console.log(`I am The ${this.name}.${msg}`)}}Copy the code

2. Classes and interfaces

Class and interface

export {} // Make sure there are no member conflicts with other examples

interface Eat {
  eat (food: string): void
}

interface Run {
  run (distance: number): void
}

class Person implements Eat.Run {
  eat (food: string): void {
    console.log('Eat gracefully:${food}`)
  }

  run (distance: number) {
    console.log('Walking upright:${distance}`)}}class Animal implements Eat.Run {
  eat (food: string): void {
    console.log('Oink oink eat:${food}`)
  }

  run (distance: number) {
    console.log(Crawl ` :${distance}`)}}Copy the code

3. An abstract class

// An abstract class can only be inherited, not new
abstract class Animal {
  eat (food: string): void {
    console.log('Oink oink eat:${food}`)
  }

  abstract run (distance: number): void
}

class Dog extends Animal {
  run(distance: number): void {
    console.log('Crawl on all fours', distance)
  }

}

const d = new Dog()
d.eat('Well, Sima.')
d.run(100)
Copy the code

Nine, appendix

Great TypeScript tutorial for getting started