【TypeScript】TS complete solution

Article directory

1. Introduction to TypeScript

(1) TypeScript

  • Background: JS is a 弱类型 language and is prone to type errors. It increases the time for checking and correcting bugs during project development, affecting efficiency
  • Definition: TypeScript, referred to as TS, is a superset of JavaScript, including all JS functions and extensions类型支持functions
  • the difference
    • JavaScript: dynamic type, 执行 periodic type checking, code执行时 found errors
    • TypeScript: static type, 编译 does type checking periodically, code执行前 finds errors; with VSCode, code 编写时 Error found

(2) Advantages

  • There is always available in the program代码提示, which reduces the time for checking and correcting bugs and improves development efficiency
  • A powerful type system improves code maintainability, making重构代码更加容易
  • Support the latest ECMAScript syntax, give priority to experience the latest syntax
  • TS type inference mechanism does not need to display annotation types everywhere in the code

2. Preparation for using TypeScript

(1) Install the toolkit for compiling TS

  • Background: Node.js/browser only recognizes JS code and needs to convert TS to JS code before it can run
  • Installation command:npm i -g typescript
    • TS package: a package for compiling TS code, providing tsc command to implement TS => JS
    • View version: tsc –v

(2) Compile and run TS code

  • Create TS: Create a new .ts file
  • Compile TS: Enter the command in the terminaltsc file.ts
  • Execute JS: Enter the command in the terminalnode file.js
    • All legal JS codes are TS codes. Basically, you only need to learn the TS type for JS.
    • JS files of the same level are generated by TS compilation, and the code does not contain type information.

(3) Simplify the steps for running TS

  • Simplified way: Use ts-node package to execute TS code in Node.js
  • Installation command:npm i -g ts-node
  • How to use:ts-node file.ts
    • ts-node does not generate js files

3. TypeScript common types

  • Type system: TS is a superset of JS, providing all the features of JS plus additional类型系统
    • JS code is all TS code
    • JS types do not check changes, TS checks variable type changes
  • Key benefit: Unexpected behavior in your code can be flagged explicitly, thereby reducing the likelihood of errors.

(1) Type annotation

1. Type annotation

  • reflect:: number
  • effect:为变量添加类型约束
let age: number = 18

2. Type alias type

  • Features: Supports the creation of type aliases for all types, generally used for complex data types
// 创建类型别名
type Person = {
    
    
  name: string
  sayHi(): void
  greet(name: string): void // 普通函数带参数的方法类型
  meet: (name: string) => void // 箭头函数带参数的方法类型
}

// 使用类型别名作为对象的类型
let person: Person = {
    
    
  name: 'jack',
  sayHi() {
    
    }
  greet(name) {
    
    
    console.log(name)
  }
  meet(name) {
    
    
      console.log(name)
    }
}

(2) Commonly used basic types

1. JS already has types

(1) Original type
  • Features: Simple type, written according to JS type name
  • 包含:number / string / boolean / null / undefined / symbol
let age: number = 18
let myName: string = '老师'
let isLoading: boolean = false
let nu: null = null
let un: undefined = undefined
let smb: symbol = symbol
(2) Array type
  • Shaping method 1:arrType[](recommendation)
  • Writing method two:Array<arrType>
// 写法一:
let numbers: number[] = [1, 3, 5]
// 写法二:
let strings: Array<string> = ['a', 'b', 'c']
(3) Object type
  • Objects in JS are composed of properties and methods, and the TS object type is描述对象结构
    • Use {} to describe object structure
    • For attribute functionkey:type Format
    • For methodfn():typeFormat
// 空对象
let person: {
    
    } = {
    
    }

// 有属性的对象
let person: {
    
     name: string } = {
    
    
  name: '同学'
}

// 既有属性又有方法的对象
let person: {
    
    
  name: string
  sayHi(): void
} = {
    
    
  name: 'jack',
  sayHi() {
    
    }
}
  • Object optional properties
    • Definition: A property or method of an object, which can be optional
    • Syntax: Use ? to represent
type Config = {
    
    
  url: string
  method?: string
}

function myAxios(config: Config) {
    
    
  console.log(config)
}
(4) Function type
  • Special point: Promise 函数参数Japanese 返回值Type of category
  • Specify individually
// 函数声明
function add(num1: number, num2: number): number {
    
    
  return num1 + num2
}

// 箭头函数
const add = (num1: number, num2: number): number => {
    
    
  return num1 + num2
}
  • Specify at the same time
    • Features:函数表达式You can add types to functions through arrow function-like syntax, which is not supported by declaring functions
type AddFn = (num1: number, num2: number) => number // 使用 type

const add: AddFn = (num1, num2) => {
    
    
  return num1 + num2
}
  • Function optional parameters
    • Features: When the parameters are not fixed, the specified type of function parameters is可选参数
    • Syntax: Add after the unfixed parameter name?
    • Note:Optional parameters can only appear at the end of the parameter list, which means that optional parameters cannot appear after optional parameters.
function mySlice(start?: number, end?: number): void {
    
    
  console.log('起始索引:', start, '结束索引:', end)
}

2. TS new type

(1) Union type
  • Definition: A type composed of two or more other types, and the representation can be any of these types
  • Syntax: Use | union
let arr: (number | string)[] = [1, 'a', 3, 'b']
(2) Custom type/type alias
  • Definition: 为任意类型Originating name
  • Syntax: Use type to declare an alias. It is recommended that aliases start with a capital letter
  • Scenario: When the same type (complex) is used multiple times, type aliases can be used to simplify the use of the type.
type CustomArray = (number | string)[]

let arr1: CustomArray = [1, 'a', 3, 'b']
let arr2: CustomArray = ['x', 'y', 6, 7]
(3)Interface
  • Definition: Add an interface for对象类型
  • Syntax: Use interface declaration, the interface name is recommended to start with I
  • Scenario: When an object type is used multiple times, the interface can be used to describe the object type to achieve reuse.
interface IPerson {
    
    
  name: string
  age: number
  sayHi(): void
}

let person: IPerson = {
    
    
  name: 'jack',
  age: 19,
  sayHi() {
    
    }
}
  • interface vs type
    • Same: you can assign types to objects
    • different
      • Interface: only specifies the type of the object, with inheritance
      • Type alias: not only specifying types for objects, but also supporting specifying types for any type
// 为对象类型提供类型接口
interface IPerson {
    
    
  name: string
  age: number
  sayHi(): void
}

// 为对象类型创建类型别名
type IPerson = {
    
    
  name: string
  age: number
  sayHi(): void
}

// 为联合类型创建类型别名
type NumStr = number | string
  • Interface inheritance
    • Syntax: Use extends inheritance
interface Point2D {
    
     x: number; y: number }
// 继承 Point2D
interface Point3D extends Point2D {
    
    
  z: number
}
(4) Tuple
  • Features: Determine元素类型and in the array元素个数
  • Syntax: tupleTuple
// 普通数组,不确定元素个数
let position: number[] = [116.2317, 39.5427]

// 元祖,确定元素类型和个数
let position: [number, number] = [39.5427, 116.2317]
(5) Literal type
  • Definition: Any JS literal (such as object, number, etc.) can be used as a type in TS
let str1 = 'Hello TS' // let 定义 str1 是变量
let str1: string = 'Hello TS'

const str2 = 'Hello TS' // const 定义 str2 是常量
const str2: 'Hello TS' = 'Hello TS'
  • Usage patterns and scenarios
    • Features: Used with union types to represent a group明确的可选值列表
    • Advantages: Compared with string types, literal types are more precise and rigorous
// 比如在贪吃蛇游戏中,游戏的方向可选值只能是上、下、左、右
// 使用自定义类型:
type Direction = 'up' | 'down' | 'left' | 'right'

function changeDirection(direction: Direction) {
    
    
  console.log(direction)
}

// 调用函数时,会有类型提示:
changeDirection('up')
(6) Enumeration (understanding)
  • Features: Similar to literal type + union type combination, it can also represent a group of明确的可选值, and also supports the direct use of枚举名称 as a type annotation
  • Syntax: Use the enum keyword to define an enumeration
    • Convention enumeration names start with a capital letter
    • Support using enum names as type annotations
// 创建枚举
enum Direction {
    
     Up, Down, Left, Right }

// 使用枚举类型
function changeDirection(direction: Direction) {
    
    
  console.log(direction)
}

// 调用函数时,通过点(.)语法访问枚举 Direction 成员
changeDirection(Direction.Up)
  • Number enumeration
    • Features: The value of the enumeration member is a number, which starts from 0 by default. You can also initialize the value of the enumeration member.
// Down -> 11、Left -> 12、Right -> 13
enum Direction {
    
     Up = 10, Down, Left, Right }

enum Direction {
    
     Up = 2, Down = 4, Left = 8, Right = 16 }
  • string enum
    • Features: The value of the enumeration member is a string. Since there is no auto-increment behavior, each member must have an initial value.
enum Direction {
    
    
  Up = 'UP',
  Down = 'DOWN',
  Left = 'LEFT',
  Right = 'RIGHT'
}
  • Enumeration implementation principle
    • Other types are only types, while enumerations are not only types, but also provide values ​​(all enumeration members have values), that is, other types are automatically removed when compiled into JS code, but enumeration types will be compiled into JS code
enum Direction {
    
    
  Up = 'UP',
  Down = 'DOWN',
  Left = 'LEFT',
  Right = 'RIGHT'
}

// 编译为以下 JS 代码
var Direction;

(function (Direction) {
    
    
  Direction['Up'] = 'UP'
  Direction['Down'] = 'DOWN'
  Direction['Left'] = 'LEFT'
  Direction['Right'] = 'RIGHT'
})(Direction || Direction = {
    
    })
(7) void type
  • Feature: Used if函数无返回值 void
function greet(name: string): void {
    
    
  console.log('Hello', name)
}

// 如果什么都不写,此时,add 函数的返回值类型为: void
const add = () => {
    
    }
// 这种写法是明确指定函数返回值类型为 void,与上面不指定返回值类型相同
const add = (): void => {
    
    }

// 如果指定返回值类型为 undefined,此时,函数体中必须显示的 return undefined 才可以
const add = (): undefined => {
    
    
  // 此处,返回的 undefined 是 JS 中的一个值
  return undefined
}
(8) any type (not recommended)
  • Features: When the value type is any, any operation can be performed on the value without code prompts. It is not recommended.
let obj: any = {
    
     x: 0 }

obj.bar = 100
obj()
const n: number = obj
  • scenes to be used
    • Use any temporarily to avoid writing long, complex types
    • Other cases that implicitly have an any type

(3) TS type method

1. Type inference

  • Definition: In TS, where the type is not specified, the type inference mechanism of TS will help provide the type.
  • Scenes
    • When declaring a variable and initializing it
    • When determining the return value of a function
// 变量 age 的类型被自动推断为:number
let age = 18

// 函数返回值的类型被自动推断为:number
function add(num1: number, num2: number) {
    
    
  return num1 + num2
}
  • use
    • Type annotations can save money and make full use of the ability of TS type inference to improve development efficiency.
    • You can use the VSCode prompt to view the type by placing the mouse on the variable name.
    • When writing code in VSCode, look more at methods and attribute types

2. Type assertion

  • Features: Developers are more specific about the type of a value than TS, and use type assertions to specify more specific types.
  • Syntax: Use the as keyword to implement type assertion, followed by a more specific type.
    • Tip: In the browser console, use __proto__ to get the type of DOM element
// 返回类型为 HTMLElement,只包含所有标签公共的属性或方法,不包含 a 标签特有的 href 等属性
const aLink = document.getElementById('link')

// 使用类型断言指定更加具体的类型,HTMLAnchorElement 是 HTMLElement 的子类型
const aLink = document.getElementById('link') as HTMLAnchorElement
  • Syntax: Use <> syntax (not recommended)
// 在react的jsx中使用会报错
const aLink = <HTMLAnchorElement>document.getElementById('link')

3、typeof

  • Features: TS provides the typeof operator to reference in type context变量或属性类型 (type query)
  • Scenario: Obtain the type based on the value of the existing variable and simplify the type writing
let p = {
    
     x: 1, y: 2 }

// 简化前
function formatPoint(point: {
    
     x: number; y: number }) {
    
    }

// 简化后
function formatPoint(point: typeof p) {
    
    }

4. TypeScript advanced types

(1) Generics

  • Definition: Under the premise of ensuring type safety, allowing functions to work with multiple types to achieve reuse, often used in functions, interfaces, and classes
  • Requirement: Create an id function that returns whatever data is passed in (that is, the parameters and return value types are the same)

1. Create a generic function

  • Syntax: Add <类型变量 Type> after the function name, which is a special type of variable, equivalent to a type container
function id<Type>(value: Type): Type {
    
     return value }

function id<T>(value: T): T {
    
     return value }

2. Call generic functions

  • Syntax: Add after the function name<指定类型>
const num = id<number>(10)
const str = id<string>('a')

// 简化泛型函数调用,省略 <指定类型>,TS 进行类型参数推断
let num = id(10)
let str = id('a')

3. Generic constraints

  • Background: The type variable Type of a generic function can represent any type, resulting in the inability to access specific properties and the need to add constraints to the generic.收缩类型
(1) Specify a more specific type
  • Method: Modify the type to the relevant specific type
function id<Type>(value: Type[]): Type[] {
    
    
  console.log(value.length)
  return value
}
(2) Add constraints
  • Create an interface: Create an interface Ixxx that describes constraints, and require the interface to provide relevant attributes
  • Add constraints: Use this interface through the extends keyword to add constraints and attributes for generics
// 创建一个接口
interface ILength {
    
     length: number }

// Type extends ILength 添加泛型约束
// 传入类型必须满足 ILength 接口要求,即 number 类型的 length 属性
function id<Type extends ILength>(value: Type): Type {
    
    
  console.log(value.length)
  return value
}

4、keyof

  • Definition: A generic type variable can have multiple types, and类型变量之间可以约束
  • Syntax: The keyof keyword receives a type variable and generates a union type of its key name.
    • The type variable Key is constrained by Type and is just one of all keys of Type. It can only access properties that exist in the object.
function getProp<Type, Key extends keyof Type>(obj: Type, key: Key) {
    
    
// keyof Type 获取 person 对象所有键的联合类型,即`'name' | 'age'`
  return obj[key]
}
let person = {
    
     name: 'jack', age: 18 }
getProp(person, 'name')

// Type extends object:Type 应该是一个对象类型
// 对象类型,应该用 object ,而不是 Object
function getProperty<Type extends object, Key extends keyof Type>(obj: Type, key: Key) {
    
    
  return obj[key]
}

5. Generic interface

  • Definition: Interfaces can be used in conjunction with generics to increase flexibility and reusability
  • grammar
    • Definition: Add after the interface name<类型变量>
    • Usage: Need to explicitly specify the specific typeIxxx<类型>
interface IdFunc<Type> {
    
    
  id: (value: Type) => Type
  ids: () => Type[]
}

// 接口中所有成员都可以使用类型变量
let obj: IdFunc<number> = {
    
    
  id(value) {
    
     return value }, // 参数和返回值类型是 number
  ids() {
    
     return [1, 3, 5] }  // 返回值类型是 number[]
}
  • Generic interfaces in JS
    • JS array is a generic interface in TS
    • When using an array, TS will automatically set the type variable to the corresponding type according to the different types of the array.
    • Use Ctrl + left mouse button (Mac: Command + left mouse button) to view specific type information
const strs = ['a', 'b', 'c']
// 鼠标放在 forEach 上查看类型
strs.forEach

const nums = [1, 3, 5]
// 鼠标放在 forEach 上查看类型
nums.forEach

6. Generic tool types

  • Definition: TS has built-in some common tool types to simplify common operations in TS
(1)Partial
  • Definition: Construct a type and set all properties of Type to optional
  • grammar:Partial<Type>
type Props =  {
    
    
  id: string
  children: number[]
}

// 构造出的新类型 PartialProps 结构和 Props 相同,但所有属性都为可选
type PartialProps = Partial<Props>
(2)Readonly
  • Definition: Construct a type and set all properties of Type to read-only
  • grammar:Readonly<Type>
type Props =  {
    
    
  id: string
  children: number[]
}

// 构造出的新类型 PartialProps 结构和 Props 相同,但所有属性都为只读
type ReadonlyProps = Readonly<Props>

// 错误演示
let props: ReadonlyProps = {
    
     id: '1', children: [] }
props.id = '2'
(3)Pick
  • Definition: Select a set of properties from Type to construct a new type
  • grammar:Pick<Type, Keys>
interface Props {
    
    
  id: string
  title: string
  children: number[]
}

// 第二个类型变量传入的属性只能是第一个类型变量中存在的属性
// 构造出来的新类型 PickProps,只有 id 和 title 两个属性类型
type PickProps = Pick<Props, 'id' | 'title'>
(4)Omit
  • Definition: Construct a new type by removing a set of attributes from Type
  • grammar:Omit<K,T>
interface Props {
    
    
  id: string
  title: string
  children: number[]
}

// 第二个类型变量传入的属性只能是第一个类型变量中存在的属性
// 构造出来的新类型 OmitProps,只有 children 属性类型
type OmitProps = Omit<Props, 'id' | 'title'>

(2) Index signature type

  • In most cases, determine the structure of the object before using it and add accurate types to the object
  • When it is impossible to determine which attributes are in the object (or any number of attributes can appear in the object), the index signature type is used
interface AnyObject {
    
    
  [key: string]: number
}
let obj: AnyObject = {
    
    
  a: 1,
  b: 2,
}
  • explain:
    1. Use [key: string] to constrain the attribute names allowed in this interface. Indicates that as long as the attribute name is of string type, it can appear in the object.
    2. In this way, any number of attributes (such as a, b, etc.) can appear in the object obj.
    3. key 只是一个占位符, can be replaced by any legal variable name.
    4. Hidden pre-knowledge:JS 中对象({})的键是 string 类型的.

Array index type signature

  • In JS, an array is a special type of object, and the keys (indexes) in the array are numerical types.
  • Moreover, arrays can also contain any number of elements. Therefore, the index signature type is also used in the generic interface corresponding to the array.
interface MyArray<T> {
    
    
  [n: number]: T
}
let arr: MyArray<number> = [1, 3, 5]
  • explain:
    1. The MyArray interface simulates the native array interface and uses [n: number] as the index signature type.
    2. This index signature type means: as long as the key (index) is of type number, it can appear in the array, or there can be any number of elements in the array.
    3. It also conforms to the premise that the array index is of type number.

(3) Mapping type

  • Mapping type:Create a new type (object type) based on the old type to reduce duplication and improve development efficiency.
    For example, the type PropKeys has x/y/z, another type Type1 also has x/y/z, and the types of x/y/z in Type1 are the same:
type PropKeys = 'x' | 'y' | 'z'
type Type1 = {
    
     x: number; y: number; z: number }
  • This is correct, but x/y/z is written twice. In this case, you can use mapping types to simplify it.
type PropKeys = 'x' | 'y' | 'z'
type Type2 = {
    
     [Key in PropKeys]: number }
  • explain:
    1. Mapping types are based on index signature types, so the syntax is similar to index signature types, also using [].
    2. Key in PropKeysIndicates that Key can be any one of the PropKeys union types, similar to forin(let k in obj).
    3. New objects of type Type2 and type Type1 created using mapped types have exactly the same structure.
    4. Note:Mapped types can only be used in type aliases, not in interfaces.

Create from object

In addition to creating new types based on union types, mapping types can also be created based on object types:

type Props = {
    
     a: number; b: string; c: boolean }
type Type3 = {
    
     [key in keyof Props]: number }
  • explain:
    1. First, execute keyof Props to obtain the union type of all keys in the object type Props, that is, ‘a’ | ‘b’ | ‘c’.
    2. Then,Key in ... means that Key can be any key name in Props.

Built-in mapping type implementation analysis

  • In fact, the previously mentionedgeneric tool types (for example, Partial) are all implemented based on mapping types.
  • For example, the implementation of Partial:
type Partial<T> = {
    
    
  [P in keyof T]?: T[P]
}

type Props = {
    
     a: number; b: string; c: boolean }
type PartialProps = Partial<Props>
  • explain:
    1. keyof TThat is, keyof Props means getting all the keys of Props, that is: ‘a’ | ‘b’ | ‘c’.
    2. Add ? (question mark) after [] to change these attributes to 可选 to realize the Partial function.
    3. The T[P] 表示获取 T 中每个键对应的类型 after the colon. For example, if it is ‘a’, the type is number; if it is ‘b’, the type is string.
    4. Ultimately, the new type PartialProps has the exact same structure as the old type Props, except that all types are made optional.

Index access type

  • The T[P] syntax just used is called in TS索引访问类型
  • Function:Used to query the type of attributes.
type Props = {
    
     a: number; b: string; c: boolean }
type TypeA = Props['a']
  • Explanation:Props['a'] represents the type number corresponding to the attribute ‘a’ in the query type Props. Therefore, the type of TypeA is number
  • Note:[] must exist in the queried type, otherwise an error will be reported.

Query the type of multiple indexes at the same time

  • Other ways to use index query types: Query multiple index types at the same time
type Props = {
    
     a: number; b: string; c: boolean }

type TypeA = Props['a' | 'b'] // string | number
  • Explanation: Use the union type of string literals to obtain the types corresponding to attributes a and b. The result is: string | number.
type TypeA = Props[keyof Props] // string | number | boolean
  • Explanation: Use the keyof operator to get the types corresponding to all keys in Props. The result is: string | number | boolean.

5. Use TS in original projects

Create new project

  • Order:npx create-react-app my-app --template typescript

  • Note: In the command line, add --template typescript to create a project that supports TS

  • Changes to project directory:

    1. There is one more file in the project root directory:tsconfig.json
      • TS configuration file
    2. In the src directory, the suffix of the file has changed, from the original .js to .ts or .tsx
      • .tsts file extension
      • .tsxThis suffix is ​​required when using React components in TS
    3. In the src directory, there are more react-app-env.d.ts files
      • .d.tsType declaration file, used to specify the type

tsconfig document introduction

  • tsconfig document introduction
  • tsconfig.json is the configuration file of the TS project, generated by tsc --init
  • All configuration items can be moved in with the mouse to view the explanation of the configuration items.
{
    
    
  // 编译选项
  "compilerOptions": {
    
    
    // 生成代码的语言版本:将我们写的 TS 代码编译成哪个版本的 JS 代码
    // 命令行: tsc --target es5 11-测试TS配置文件.ts
    "target": "es5",
    // 指定要包含在编译中的 library
    "lib": ["dom", "dom.iterable", "esnext"],
    // 允许 ts 编译器编译 js 文件
    "allowJs": true,
    // 跳过类型声明文件的类型检查
    "skipLibCheck": true,
    // es 模块 互操作,屏蔽 ESModule 和 CommonJS 之间的差异
    "esModuleInterop": true,
    // 允许通过 import x from 'y' 即使模块没有显式指定 default 导出
    "allowSyntheticDefaultImports": true,
    // 开启严格模式
    "strict": true,
    // 对文件名称强制区分大小写
    "forceConsistentCasingInFileNames": true,
    // 为 switch 语句启用错误报告
    "noFallthroughCasesInSwitch": true,
    // 生成代码的模块化标准
    "module": "esnext",
    // 模块解析(查找)策略
    "moduleResolution": "node",
    // 允许导入扩展名为.json的模块
    "resolveJsonModule": true,
    // 是否将没有 import/export 的文件视为旧(全局而非模块化)脚本文件
    "isolatedModules": true,
    // 编译时不生成任何文件(只进行类型检查)
    "noEmit": true,
    // 指定将 JSX 编译成什么形式
    "jsx": "react-jsx"
  },
  // 指定允许 ts 处理的目录
  "include": ["src"]
}

(1) Typescript declaration file

  • Background: Almost all JS applications will introduce third-party libraries to complete task requirements. Third-party libraries, whether written in TS or not, have corresponding TS types.
  • Definition: Typescript declaration files provide type information for existing JS libraries, with mechanisms such as code prompts and type protection.
  1. Two file types of TS
  2. Instructions for using type declaration files

1. TS two file types

  • .ts files
    • 既包含类型信息又可执行代码
    • Can be compiled into a .js file and then execute the code
    • Purpose: A place to write program code
  • .d.ts files
    • 只包含类型信息type declaration file
    • No .js file will be generated, executable code is not allowed, it is only used to provide type information
    • Purpose: Provide type information for JS
  • Summary: .ts is implementation (code implementation file); .d.ts is declaration (type declaration file)

2. Instructions for using type declaration files

(1) Built-in type declaration file
    • TS provides declaration files for all standardized built-in APIs available to the JS runtime
const strs = ['a', 'b', 'c']
// 鼠标放在 forEach 上查看类型
strs.forEach
  • In fact, these are all built-in type declaration files provided by TS
  • You can view the contents of the built-in type declaration file through Ctrl + left mouse button (Mac: Command + left mouse button)
  • For example, when viewing the type declaration of the forEach method, VSCode will automatically jump to the lib.es5.d.ts type declaration file
  • Of course, BOM and DOM APIs such as window and document also have corresponding type declarations (lib.dom.d.ts)
(2) Type declaration file of third-party library
  • Commonly used third-party libraries have corresponding type declaration files
    • The library comes with type declaration files, such as axios, see node_modules/axios directory
    • Provided by DefinitelyTyped, a github repository that provides high-quality TS type declarations
    • During actual project development, the third-party library does not have its own declaration file, and VSCode will give clear instructions.
    • TS official documentation provides a page where you can query the @types/* library
(3) Create your own type declaration file
  • Sharing type within project
    • The same type is used in multiple .ts files. At this time, you can create .d.ts files to provide this type and achieve type sharing
    • Steps
      • Create the index.d.ts type declaration file.
      • Create the type that needs to be shared and export it using export
      • In the .ts file that needs to use the shared type, import it through import
  • Provide type declarations for existing JS files
    • background
      • When migrating a JS project to a TS project, in order to make the existing .js files have type declarations
      • Become a library author and create libraries for others to use
(4) Instructions for using type declaration files
  • Note: .js files can be used in TS projects. When importing .js files, TS will automatically load the .d.ts file with the same name as .js to provide type declarations.
  • declare: used for type declaration, declaring a type for a variable that already exists elsewhere (such as a .js file) instead of creating a new variable
    • The declare keyword can be omitted for explicit TS types such as type and interface.
    • let, function, etc. have dual meanings (can be used in JS and TS), and must use the declare keyword to clearly specify that it is used for type declaration.
let count = 10
let songName = '痴心绝对'
let position = {
  x: 0,
  y: 0
}

function add(x, y) {
  return x + y
}

function changeDirection(direction) {
  console.log(direction)
}

const fomartPoint = point => {
  console.log('当前坐标:', point)
}

export { count, songName, position, add, changeDirection, fomartPoint }

Define type declaration file

declare let count:number

declare let songName: string

interface Position {
  x: number,
  y: number
}

declare let position: Position

declare function add (x :number, y: number) : number

type Direction = 'left' | 'right' | 'top' | 'bottom'

declare function changeDirection (direction: Direction): void

type FomartPoint = (point: Position) => void

declare const fomartPoint: FomartPoint

export {
  count, songName, position, add, changeDirection, FomartPoint, fomartPoint
}

(2) Add TS to existing projects

  • CRA adds ts document
  • step
    • Installation package:yarn add typescript @types/node @types/react @types/react-dom @types/jest
    • Change jsconfig.json to path.tsconfig.json
    • Copy the configuration in tsconfig.json in the TS project originally created through React scaffolding to our own project
    • Create path.tsconfig.json file and take the contents of the original jsconfig.json file
{
    
    
  "compilerOptions": {
    
    
    "baseUrl": "./",
    "paths": {
    
    
      "@/*": ["src/*"],
      "@scss/*": ["src/assets/styles/*"]
    }
  }
}

  • In tsconfig.json, add configuration
{
    
    
  // 添加这一句
  "extends": "./path.tsconfig.json",

  "compilerOptions": {
    
    
    ...
  }
}
  • Copy src/react-app-env.d.ts in the TS project created through React scaffolding to the src directory of your own project
  • Restart project
  • illustrate
    • When using TS in a project, you can include both js files and ts files.
      • .js, .jsx (when using JS, the file suffix corresponding to the React component)
      • .ts, .tsx (when using TS, the file suffix corresponding to the React component), .d.ts
    • Recommended mode when adding TS to an existing project
      • Use TS for new features
      • For functions that have been implemented, you can continue to keep the JS file and slowly modify it to TS.
    • The file suffix corresponding to the React component is modified to:.tsx
    • The file suffix corresponding to the tool function, change it to: .ts or add a type declaration file to it .d.ts

Guess you like

Origin blog.csdn.net/weixin_64210950/article/details/128088432