“This is the 25th day of my participation in the First Challenge 2022. For details: First Challenge 2022.”

declare

When using third-party libraries, many third-party libraries are not written in TS, so we need to reference its declaration file to obtain the corresponding code completion, interface prompts and other functions.

For example, if you use Vue directly in TS, an error will be reported,

const app = new Vue({
  el: '#app'.data: {
    message: 'Hello Vue! '}})Copy the code

In this case, we can use the DECLARE keyword to define the type of Vue.

interface VueOption {
    el: string.data: any
}

declare class Vue {
    options: VueOption
    constructor(options: VueOption)}const app = new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue! '}})
Copy the code

Using the DECLARE keyword tells the TS compiler that the type of the variable (Vue) has already been defined elsewhere, so you can use it without reporting an error.

Note that Declare Class Vue does not actually define a class, only the type of class Vue, which is only used for compile-time checks and will be deleted in the compile result. It compiles as follows:

const app = new Vue({
  el: '#app'.data: {
    message: 'Hello Vue! '}})Copy the code

.d.ts

Usually we put declarations in a separate file (vue.d.ts), which is the declaration file, with the suffix.d.ts.

// src/Vue.d.ts

interface VueOption {
    el: string.data: any
}

declare class Vue {
    options: VueOption
    constructor(options: VueOption)}Copy the code
// src/index.ts

const app = new Vue({
  el: '#app'.data: {
    message: 'Hello Vue! '}})Copy the code

In general, TS parses all *. Ts files in a project, including those ending in.d.ts. So when we put vue.d. ts into the project, all the other *.ts files can get the Vue type definition.

The/path/to/project ├ ─ ─ the SRC | ├ ─ ─ but ts | └ ─ ─ Vue. Which s └ ─ ─ tsconfig. JsonCopy the code

Using the Tripartite library

So when we use tripartite libraries, do all the tripartite libraries have to write a bunch of decare files?

The answer is not necessarily, it depends on whether there is a TS type package for the tripartite library in the community (usually there is).

The community uses @types to centrally manage third-party library declaration files, managed by DefinitelyTyped

Like installing the LoDash type package,

npm install @types/lodash -D
Copy the code

Once installed, you can use LoDash normally in TS, and you don’t need to do anything else.

Of course, if a library is written in TS, you don’t have to worry about type files, such as Vue3.

Write your own declaration

For example, if you wrote a request module called myFetch, the code is as follows:

function myFetch(url, method, data) {
    return fetch(url, {
        body: data ? JSON.stringify(data) : ' ',
        method
    }).then(res= > res.json())
}

myFetch.get = (url) = > {
    return myFetch(url, 'GET')
}

myFetch.post = (url, data) = > {
    return myFetch(url, 'POST', data)
}

export default myFetch
Copy the code

Now that the new project uses TS, to continue using myFetch in the new project, you have two options:

  • Rewrite myFetch with TS, the new project quotes the rewritten myFetch
  • Reference myFetch directly and write a declaration file to it

If you choose option two, you can do this,

type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'DELETE'

declare function myFetch<T = any> (url: string, method: HTTPMethod, data? :any) :Promise<T>

declare namespace myFetch { // Use a namespace to declare properties and methods under an object
    const get: <T = any>(url: string) => Promise<T> 
    const post: <T = any>(url: string, data: any) => Promise<T>
}
Copy the code

The tricky thing is that you need to configure it, and there are two options,

  1. To create anode_modules/@types/myFetch/index.d.tsFile, storagemyFetchModule declaration file. No additional configuration is required, howevernode_modulesThe directory is not stable, the code is not saved in the repository, the version can not be backtracked, and there is a risk of accidentally deleted, so this solution is not recommended, generally only for temporary testing.
  2. To create atypesDirectory, dedicated to managing self-written declaration files, willmyFetchThe declaration file is placed intypes/myFetch/index.d.tsIn the. This mode needs to be configuredtsconfig.jsonIn thepaths 和 baseUrlField.
// tsconfig.json
{
    "compilerOptions": {
        "module": "commonjs"."baseUrl": ". /"."paths": {
            "*": ["types/*"]}}}Copy the code

Let’s test it out, call it in,

Return value alert,

The way to abbreviate,

It feels better to rewrite directly in TS than to write declarations for older projects without having to maintain type modules.

Many libraries used in normal development are now basically rewritten in TS.

summary

This article only covers the tip of the iceberg of TS documentation, but more on the official documentation.

You can also read this article if you think official documents are difficult to read, but there are also a lot of knowledge points.

Learning the knowledge of this article, start the project certainly no problem, I am not high on their own requirements, can work on the line, learn too much hair will fall light!

The issue of

Easily take down TS generics

What is the difference between interface and type in TS?

TS Advanced Types

TS type inference

TS enumeration type

Easy to understand the basic knowledge of TS summary