当前位置:网站首页>Typescript type declaration file (III)

Typescript type declaration file (III)

2022-06-12 18:03:00 Out of the autistic bird

TS Type declaration file

Type declaration file Overview

In the project TS Will eventually be compiled into JS, When we use external third-party libraries , How to use TS Grammar .

Type declaration file : Used for existing JS The library provides type information

TS file type

  • .ts file
    1. Contains both type information and executable code
    2. Can be compiled as js file , Then execute the code
    3. purpose : Where the program code is written
  • .d.ts file
    1. A type declaration file that contains only type information
    2. Will not generate js file , Only used to provide type information
    3. purpose : by JS Provide type information

If you want to JS The library provides type information , You use .d.ts file

Use an existing type declaration file

Built in API Type declaration file

windows The system presses ctrl Key click built in API To open the file

 Please add a picture description

 Please add a picture description

Use the type declaration file of the third-party library
  • The type declaration file comes with downloading the library
  • from DefinitelyTyped Provide

stay TypeScript Search and download on the official website

Create your own type declaration file

Shared classes within the project

If more than one ts All files use the same type , You can create .d.ts The file provides this type , Implement type sharing

  1. establish index.d.ts Type declaration file
  2. Create a type that needs to be shared , Use export export
  3. Use through import Import , Omit .d.ts
For what is JS The file provides a type declaration

Importing a js When you file ,TS Automatically loaded on js The document has the same name .d.ts file

Use declare keyword : Used for type declaration , by js The variable declaration type already exists in the file , Instead of creating a new variable

// .js file 
let count = 1

// .d.ts file 
declare let count: number

about type、interface these TS Peculiar , You can omit declare; about let、function etc. JS and TS Can be used , You should use declare keyword

原网站

版权声明
本文为[Out of the autistic bird]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/163/202206121758170598.html