By understanding JavaScript, TypeScript saves you time catching errors and providing fixes before you run code.

Any browser, any OS, anywhere JavaScript runs. Entirely Open Source.

A, use,

  1. In the root directory, generate the package file,yarn init --dev
  2. Download typescript dependencies,yarn add typescript --dev
  3. Compile TS using terminal instructions,Yarn TSC File name
  4. Generate a TypeScript configuration file,yarn tsc --init
  • Compile the TS file, YARN TSC

  • Compile the error file in Chinese, yarn TSC –locale zh-cn

2. TS configuration file

Executing YARN TSC –init generates a configuration file in the root directory: tsconfig.json

(You can also set strict mode and so on.)

Module scope

To avoid global naming conflicts, you need to make the TS file a module file. (Or put it in IIFE.)

export {}
Copy the code

Four, type,

1. Primitive type

// Primitive type

const a:string = 'foo';

const b:number = 123;

const c:boolean = true; // false

// const d:boolean = null;

const e:void = undefined;

const f:undefined = undefined;

const g:null = null;

const h:symbol = Symbol(a);// You need to modify the target or lib of the configuration file for the new type of es2015

// The library is the declaration of the built-in object

// const error:string = 100;
Copy the code

2. Object type

/ / the Object type
export {} // Avoid scope variable conflicts

// All object types except the original type
const foo: object = function () {} / / / / [] {}

// Constraints on the type of an object: object literals
const obj: {foo: number.bar: string} = {
  foo: 123.bar: 'str'};Copy the code

3. Array types

// Array type
export {}

const arr1: Array<number> = [1.2.3];

const arr2: number[] = [4.5.6]; / / the commonly used

function sum (. args:number[]) {
  return args.reduce((prev, current) = > prev + current, 0);
}
sum(1.2.3.4);
Copy the code

4. Tuple type

// Tuple type specifies the number and type of elements in an array
export {}

const tuple: [number.string] = [1.'str'];

// const age:number = tuple[0];
// const name = tuple[1];

const [age, name] = tuple;

// ----------------
Object.entries({
  foo: 123.bar: 456
})
Copy the code

5. Enumeration types

// Enumeration type

export {}

// const PostStatus = {
// Draft: 0,
// Unpublished: 1,
// Published: 2
// }

// enum PostStatus {
// Draft = 0,
// Unpublished = 1,
// Published = 2
// }

// enum PostStatus {
// Draft = 6,
// Unpublished, // 7
// Published // 8
// }

// String enumeration
// enum PostStatus {
// Draft = "aaa",
// Unpublished = "bbb",
// Published = "ccc"
// }

// Constant enumeration
const enum PostStatus {
  Draft,
  Unpublished,
  Published
}

const post = {
  title: 'this is a title of the current post'.content: 'Hello TypeScript! This is a typed superset of JavaScript.'.status: PostStatus.Draft // 1/2
}
Copy the code

6. Function types

// Function type

export {}

function func1 (a:number, b:number = 10. rest:number[]) :string {
  return 'func1'
}
func1(1.2);
func1(1);
// func1(1, 2, 3); 

// Add? To 'b' , b becomes optional
function func2 (a:number, b? :number) :string {
  return 'func2'
}
func2(1.2);
func2(1);

/ / = = = = = = = = = = = = = = = = = = = = =
// parameter type limit of func3 + type limit of return value
const func3: (a: number, b: number) = > string = function (a:number, b:number) :string {
  return 'func3'
}
Copy the code

7. Any type

// Any type
export {}

function stringify (value: any) {
  return JSON.stringify(value);
}

stringify(123);
stringify('string');
stringify(true);

let foo: any = '123';
foo = 123;

// The any type is unsafe
Copy the code

8. Implicit type inference

// Implicit type inference

export {}

let age = 18; // This is inferred as number

// age = '123';

let foo; / / any type

foo = 123;

foo = 'str';
Copy the code

Type assertion

// Type assertion

export {}

const nums = [1.2.3.4.5];

const res = nums.find(n= > n > 2);

// const square = res * res;

const num1 = res as number; // Consider res explicitly as a numeric type

const num2 = <number>res; // Do not use in JSX
Copy the code

Five, the interface

// The structure of the interface constraint object must conform to the interface specification
// Optional member Read-only member Dynamic member
export {}

interface Post {
  title: string
  content: stringsubtitle? :string // Optional member
  readonly summary: string // Read-only member
}

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

printPost({
  title: 'typescript'.content: 'a surperset of js'.summary: 'a description'
})

// --------------------------
// Dynamic member
interface Cache {
  [key: string] :string
}

const cache: Cache = {}
cache.foo = '123'
cache.bar = '456'
Copy the code

Six, class,

/ / class
export {}

class Person {
  // Define the type of an attribute in an object instance
  name: string // = 'init name'
  age: number

  constructor (name: string, age: number) {
    this.name = name
    this.age = age
  }

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

1. Modifiers in a class

// Class access modifier
export {}

class Person {
  // Access modifiers: public Public attributes
  public name: string // = 'init name'
  // Access modifiers: private private properties (cannot be accessed externally)
  private age: number
  // Access modifiers: protected protected properties (not externally accessible, but accessible in subclasses)
  protected gender: boolean

  constructor (name: string, age: number) {
    this.name = name
    this.age = age
    this.gender = true
  }

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

class Student extends Person {
  / / private class
  private constructor (name: string, age: number) {
    super(name, age)
    console.log(this.gender) // Gender can be accessed in subclasses
  }

  static createObj (name: string.age: number) {
    return newStudent(name, age); }}const mike = new Person('mike'.18);
console.log(mike.name)
// console.log(mike.age)
// console.log(mike.gender)

const jack = Student.createObj('jack'.20);
Copy the code

2. Read-only attribute

// The read-only type of the class
export {}

class Person {
  public name: string // = 'init name'
  private age: number
  // The read-only attribute readonly
  protected readonly gender: boolean

  constructor (name: string, age: number) {
    this.name = name
    this.age = age
    this.gender = true
  }

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

const mike = new Person('mike'.18);
console.log(mike.name)
Copy the code

3. Classes and interfaces

Class and interface
export {}

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

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

class Human implements Eat.Run {
  eat (food: string) :void {
    console.log(` ate${food}`)
  }
  run (distance: number) :void {
    console.log(` go${distance}`)}}class Animal implements Eat.Run {
  eat (food: string) :void {
    console.log(Eat `${food}`)
  }
  run (distance: number) :void {
    console.log(` climbed${distance}`)}}Copy the code

4. An abstract class

/ / abstract classes
export {}

abstract class Animal {
  eat (food: string) :void {
    console.log('Eat eat eat', food)
  }
  abstract run (distance: number) :void
}

class Dog extends Animal {
  run (distance: number) :void {
    console.log('Take a walk', distance)
  }
}

const d = new Dog();
d.eat('cakes');
d.run(100);
Copy the code

Seven, generics

// Generics do not specify the declared type when they are declared, and pass the specific type when they are called
export {}

function createNumberArray (length: number, value: number) :number[] {
  const arr = Array<number>(length).fill(value)
  return arr
}

function createStringArray (length: number, value: string) :string[] {
  const arr = Array<string>(length).fill(value)
  return arr
}

/ / generics
function createArray<T> (length: number, value: T) :T[] {
  const arr = Array<T>(length).fill(value)
  return arr
}

const res = createNumberArray(3.100) / / [100, 100, 100]
const res2 = createArray<string> (3.'100') / / [' 100 ', '100', '100')
Copy the code

Type declaration

// Type declaration
import { cameCase } from 'lodash'

// Declare the function type
declare function cameCase(input: string) :string

const res = cameCase('typed javascript')

export {}
Copy the code

If not, use NPM I — save-dev@types /lodash to download the ts type declaration file.