A, compile,

–outDir Specifies the output directory for compiled files

TSC --outDir Directory of the specified folder relative to the current command line location Ts file address to compile 🌰 :// compile index.ts from SRC to dist
tsc --outDir ./dist ./src/index.ts
Copy the code

–target Specifies the code version target to compileES3

// compile SRC index.ts as ES6 JS and store it in dist
tsc --outDir ./dist --target ES6 ./src/index.ts
Copy the code

— Watch runs in monitor mode and automatically compiles when TS files change

// compile SRC index.ts as ES6 JS and store it in dist
tsc --outDir ./dist --target ES6 --watch ./src/index.ts
Copy the code

Compiling configuration files tsconfig.json

{
  // Compile configuration options
    "compilerOptions": {
    // Specify the output directory relative to the current tsconfig.json file path
    "outDir": "./dist".// Specify the compiled version
    "target": "es6".// Listen mode
    "watch": true
  },
    
  // include specifies the directory and file to look for in the current compilation, relative to the current tsconfig.json
  // ** : all directories (including subdirectories)
  // * : all files, also can specify the type
  "include": [
    "./src/**/*.ts"]}// The TSC command is used to execute tsconfig.json
Copy the code

Specifies the compiled configuration file to load

Using –project or -p to specify a configuration file directory will load the tsconfig.json file in that directory by default, or you can specify a specific configuration file

Second, the type

Dynamically typed language

define

A language that does data type checking only during program execution, such as JavaScript

advantages

  • Disadvantages of statically typed languages

disadvantages

  • Advantages of statically typed languages

Statically typed language

define

A language in which data type checking is performed during program compilation, such as Java

advantages

  • Potential errors can be found during compilation (with the IDE, the compiler, and even during coding) to prevent errors from occurring after the program is run in production
  • Coding specification is conducive to team development and collaboration, and also more conducive to large-scale project development and project reconstruction
  • With IDE, editor to provide more powerful code intelligence hints and checks
  • Code is documentation

disadvantages

  • trouble
  • Lack of flexibility

Type system

Two important components

  • Type annotation (definition, annotation) – typing
  • Type-checking – type-checking

Type test

As the name suggests, it checks the type of data. Notice that the emphasis here is on the word type.

Type system to detect types, not specific values (although, sometimes also can readings), such as the scope of a parameter (1-100), we can’t depend on the type system to complete the test, it should be our business logic, type system test is whether its value type for the digital!

Type annotation

Type annotation is to add type description to data (variable, function (parameter, return value)) in code. When a variable or function (parameter) is annotated, it cannot store or pass in a type that does not conform to the annotation type.

  • With annotations, the Typescript compiler can check the data for type-validity based on the annotations.
  • With annotations, various editors, ides, and so on can do intelligent prompts.
Data carrier: typelet name: string = 'Jerry'
Copy the code

Basic simple type annotation

1. Basic Type – Basic type

let name: string = 'Jerry'
let isOk: boolean = true
let num: number = 1
Copy the code

2. Empty and undefined types – Base types

Since there is only one value in null and undefined, it means that the change cannot be changed when a variable is marked as null and undefined

let a: null
let b: undefined
Copy the code

By default null and undefined are subtypes of all types, which means that variables of other types can be set to null and undefined

let num: number = 1
num = null

// There is a problem, TS can not detect but run error
num.toFixed(1)

StrictNullChecks set strictNullChecks to true
Copy the code

If a variable is declared but not assigned, the value is undefined, but if it is also untyped, the default type is any

// The type is string and the value is undefined
let name: string
// The type is any and the value is undefined
let num
Copy the code

The element may be null

let el = document.querySelect('div')
// Add judgment
if (el) {
  el.style.display = 'none'
}
Copy the code

3. Object type – Non-basic type

// A, JS built-in Object types, such as Object, Array, Date... , can be specified by the object's constructor or class
  let data: Object = {}
  let arr: Array<nubmer> = [1.2.3]
  let d: Date = new Date(a)// B. User-defined object types
  // 1
  let user: {name: string.age: number} = {
    name: 'Jerry'.age: 20
  }
  user.sex = 'male' // Error

  // 2
  interface Person {
    name: string
    number: number
  }
  let user: Person = {
    name: 'Jerry'.age: 20
  }
  // Interface can only be used as a type annotation, not as a concrete value.
  // It is only an abstract structure definition, not an entity, no concrete function implementation

  // 3. Define class or constructor
  class Person {
    constructor (public user: string.public age: number) {}}let user: Person = new Person('Jerry'.35)

  // C
  let a: string // => Character string
  a = '1' // Right
  a = new String('1') // Error

  let a: String// => String object
  a = '1' // Right
  a = new String('1') // Right

  // If a string object has a string, it does not have a string.
  // String any string object must have one
Copy the code

4. Array types – non-base types

Array types in TypeScript must be consistent, so when annotating an array type, annotate the data type stored in the array as well

A. Use generic annotationslet arr = Array<number> = []
  arr.push(100) // Right
  arr.push('Jerry') // ErrorB. Simple labelinglet arr2: string[] = []
  arr2.push('Jerry') // Right
Copy the code

5. Tuple type – Special type

Tuples are like arrays, but do not have to store the same element type, but note that:

  • The number of initialized data and corresponding annotation types must be consistent
  • Out-of-bounds (new) data must be one of the types in the tuple annotation (out-of-bounds data may not correspond to the sequence-union type)
// Declare a string, array type, then the initialization data must also be string and number type and must have the corresponding data of these two types
let data: [string.number] = ['Jerry'.20]
data.push('Tom') // Right
data.push(30) // Right
data.push(true) // Error
Copy the code

6. Enumeration types – Special types

The way an organization collects a set of related data, through enumeration we can give a set of related meaningful data some friendly names

  • The key must be a string, not a number
  • Value can only be a number or a string

If value is a number, it is called enumeration of numeric types.

If value is a string, it is called string type enumeration.

Value The default value is a number: 0

  • Enumeration values can be omitted, if omitted:

If the first enumeration value defaults to 1, the non-first enumeration value is the previous numeric enumeration value +1

If the previous enumeration value is a string, the subsequent enumeration value must be manually assigned

  • Enumeration values are read-only (constant) and cannot be modified after initialization
// Enumeration names are generally all uppercase
enum HTTP_CODE {
  DEFAULT, // Default is 0
  OK = 200,
  NOT_FOUND = 404,
  METHOD_NOT_ALLOWED // The default value is 405
}
// Cannot assign after definition is complete
HTTP_CODE.OK = 1 // Error

/ / value
HTTP_CODE.OK / / 200
HTTP_CODE['200'] // 'OK'
Copy the code

7. No value type – Special type

Represents a type without any data. It is usually used to annotate the return value type of a function with no return value. The default annotation type of the function is void

function fn () :void {
 // No return or return undefined
}

Json if strictNullChecks is set to false, return NULL is allowed
Copy the code

8. Never type – Special type

When a function never returns, it returns never, unlike void, which executes a return but has no value. Never never returns, such as throwing an error that causes the function to abort

function fn() :never {
  throw new Error('error')}Copy the code

Any type – Special type

Sometimes we don’t know exactly what type this value is or we don’t need to type check it, we can label it any, okay

let a: any
a = 1 // Right

let b: number
b = a // Right
Copy the code
  • If a variable declaration is unassigned and untyped, the default isanytype
  • Any type can be assigned toanytype
  • anyA type can also be assigned to any type
  • anyA type has arbitrary attributes and methods

*tsconfig.json Configures noImplicitAny. If noImplicitAny is set to true, the any type is prohibited

10. Unknown Type Unknow (Version 3.0 Added) – Special type

New in version 3.0, the security any is different from any:

  • unknowCan only be assigned tounknow,any
  • unknowThere are no properties or methods
let a: any = 'Jerry'
let b: number = 1
b.toFixed(2) // Right

b = a
b.toFixed(2) // The editor does not report an error, but it is actually an error

let a: unknow = 'Jerry'
let b: number = 1
d = a // Error, unknow can only be assigned to unknow and any
Copy the code

11. Function types

Functions are important in JavaScript, but also in TypeScript. Similarly, functions have their own type formatting annotations

  • parameter
  • The return value

Function name (parameter 1: parameter 1 type, parameter 2: parameter 2 type): return value type {}

function add (x: number, y: number) :number {
  return x + y
}
Copy the code

The interface of the interface

Annotate complex data types (objects)

interface Person {
  name: string
  age: number
}

let user: Person = {
  name: 'Jerry'.age: 20
}

// Note: An interface is a type and cannot be used as a value
let user = Person // Error
Copy the code

attribute

interface Person {
  name: string
  age: number
  
  // 1, optional attributes, can be transmitted or notsex? :string
  
  // 2, read-only attribute, assigned value during initialization, cannot be modified later
  readonly hobby: string
  
  // 3, any attribute, index can only be string or number
  [key: string] :string // Allows a string attribute to be extended
  [key: number] :number // Allows an attribute of numeric type to be extended
}

let user: Person = {
  name: 'Jerry'.age: 20.hobby: 'basketball'
}

user.education = 'bachelor' // Any attribute
Copy the code

🔥 Note: When both numeric and string indexes exist, the numeric value type must be the value type or subtype of the string

interface Person1 {
  [key: string] :string
  [key: number] :number // Error
  // number is not a subtype of string
}

interface Person2 {
  [key: string] :Object
  [key: number] :Date // Right
  Date is a subtype of Objet
}
Copy the code

Use interfaces to describe functions

interfaceInterface name {(parameter1Parameters:1Type, parameter2Parameters:2Type): return value type}interface User {
  (name: string.age: number) :string
  // Do not add key, that is fn, so instead of defining a function, we define an object that has a method of fn under it
  fn (name: string.age: number) :string
}

let userFn: User = function (name, age) {
  return `${name}The age is${age}At the age of `
}

// Use the scenario to define the callback function
interface CallBack {
  (a: nummbr, b: number) :number
}
function todo (callback: CallBack) {
  const result = callback(1.2)
}

todo(function (a: number, b: number) :number {
  return a + b
})
Copy the code

Interface with

Multiple interfaces with the same name are merged into one interface

interface Person {
  name: string
}

interface Person {
  age: number
  // Specify a method named fn under an object
  fn (a: string) :string
}

interface Person {
  age: number // Right
  age: string // Error
  // Specify a method named fn under an object
  fn (a: number) :number // Right
}

let user: Person = {
  name: 'Jerry'
  age: 20.fn: function (a: any) :any {}}Copy the code
  • If the merged interface has non-function members of the same name, ensure that they are of the same type; otherwise, an error will be reported
  • Functions with the same name in the interface are overloaded

5. Advanced types

The joint type

A combined type can also be called a multiple-choice type, and can be used when we want to label a variable as one of multiple types, [or]

function css (ele: Element, attr: string, value: string | number) {}

css(el, 'width'.'100px') // Right
css(el, 'opacity'.0) // Right
css(el, 'opacity'[1.2]) // Error
Copy the code

Cross type

A crossover type, also known as a merge type, can combine multiple types together to form a new type, [and] relationship

interface Type1 {
  x: number
  y: string
}

interface Type2 {
  z: number
}

const data: Type1 & Type2 = {
  x: 1.y: 'Jerry'.z: 2
}
Copy the code

Literal type

When we want to annotate not a type but a fixed value, we can use literal types, often in conjunction with union types (or).

The function user (name: string, sex: 'male' | 'female') {}Copy the code

Type the alias

When type annotations are complex, we can use the type keyword to give the annotation a relatively simple name

// The literal type alias
type Sex = 'male' | 'woman' | 'unknown'
// Combine type aliases
type Age = string | number
function user (name: string, sex: Sex, age: Age) {}

// Alias of the function type, slightly different from interface
type callback = (a: string) = > string
let fn: callback = function (a) {}

// Or directly
let fn: (a: string) = > string= > function (a) {}
Copy the code

Difference between interface and Type

  • Describe the differences:
    • interfaceCan only be describedobject/class/functionThe type of;
    • typeCan describe all data
  • Name difference:
    • The same nameinterfaceAutomatic merge, easy to expand;
    • typeCan’t wish

Type inference

While explicitly annotating types every time is cumbersome, TypeScript provides a more convenient feature: type derivation.

The TypeScript compiler automatically deduces type annotations from the context. This happens when:

  • Initialize a variable
  • Sets the default parameter values of the function
  • Return function value
// Automatically infer that x is number
let x = 1

// Type 'a' cannot be assigned to type number
x = 'a'

// Function parameter types and function return values are automatically inferred based on the corresponding default values and return values
// Assume that a is number based on the default parameter values
function fn (a = 1) {
  // Infer that the return value is number
  return a * a
}
Copy the code

Types of assertions

Sometimes, we may specify a more precise type to narrow down the type annotation, for example:

let img = document.querySelector('#img')
img.src = 'xxx' // Error => Attribute "SRC" does not exist on type "Element"
Copy the code

I can see that the img type is Element, and Element is a generic Element type. If we access SRC, we need to type it more precisely: The HTMLImageElement type, at which point we can use type assertion, which is similar to a type conversion:

let img = <HTMLImageElement>document.querySelector('#img')
/ / or
let img = document.querySelector('#img') as HTMLImageElement

img.src = 'xxx' // Right
Copy the code

Note: An assertion is a prediction and does not have an actual effect on the data itself, i.e., it is like a conversion, but it is not actually converted