Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use jQuery in typescript

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Most people do not understand the knowledge points of this article "how to use jQuery in typescript", so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to use jQuery in typescript" article.

Introduction

What is a description file? Before answering this question, let's first think about such a question, typescript and javascript are not interlinked in principle, so before typescript comes out, all javascript can't be used, such as jQuery, if it can't be used, is it a pity? therefore, in order to solve this problem, typescript produced a description file, which is what we often see. D.ts files, whose purpose is to get through javascript and typescript, and to describe the missing types for javascript files

Initialization

For better and more intuitive learning, initialize a project first. Our aim is to mix jQuery and typescript.

To put it simply, the initialization command is as follows

/ / initialize npm

Npm init

/ / initialize typescript

Tsc-init

Then create a new html file and create a new one in the same directory. Ts file, which introduces the cdn of jQuery into html, such as:

Or create a new Vue3+typescript project using the scaffolding of Vue, and introduce the cdn of the jquery above the index.html under its public

Description file

We will use. The file at the end of the d.ts is called the description file. It doesn't matter what the preceding text is, whether it is a.d.ts or jQuery.d.ts. Its function is to describe the type for the js file.

This involves the first knowledge point, the keyword: declare, which represents a declaration followed by the type of code that defines the type. Let's take a look at the specific analysis.

Define global variables

For example, we are now in. Write jquery code in ts file

; $(function () {}) ()

This is a common method of executing functions immediately in the jquery era, if we directly in. Write in ts, it will report an error, and it will prompt you to install the type of jq in @ types. The error is as follows:

Cannot find name'$'. Do you need to install type definitions for jQuery? Try npm i @ types/jquery and then add jquery to the types field in your tsconfig

In fact, we don't have the type of jquery in types, so in order for it to work in. Ts is working properly, and we need to do it in. Make a declaration for it in the description file d.ts:

Declare const $: (param: () = > void) = > void

Analyze this declaration and make a split with the following outer layer

$() / / this is a jquery function

Corresponding declaration

$: () = > void

If you take a closer look, you should be able to understand, declare that this is a function, and it does not return a value, and then look at the parameter, this is a function, and it does not return a value, and then look at the parameter, this is a function, and it does not return a value, and then look at the parameter, () there is a function () {} A function type is also nested in the corresponding declaration. Obviously, function () {} is an argument to $(), this parameter is a function, and it does not return a value.

/ / so in the outer declaration, add a parameter and set the function type for it with no return value

Param: () = > void

Define global functions

Take the example above.

; $(function () {}) ()

one

This is obviously also a function, and we can also declare it as a function.

Declare function $(params: () = > void): void

one

After the above analysis, this should be clear, declared a function $, it does not return a value, so it is void, but it has a parameter, the parameter is a function, and there is no return value

At this point, some friends who are familiar with jQuery may ask that there are other uses of jQuery. For example, it can select a node and add content to it. The code is as follows

$(function () {)

$("body") Append ("oliver")

})

If it is written in this way, it will still report errors, yes, this way of writing will continue to report errors, because we do not have this way of writing. Defined in d.ts, so, for this use, we will write a type description

/ / Type

Declare function $(

Params: string

): {

Append: (params: string) = > {}

}

This time the function of $() is a string, and its return value doesn't know exactly what it is, but since it works. In this way, append at least means that it is an object, and only objects have it in js. This operator is immediately followed by a method of append, which takes an argument, which is a string.

It's almost easy to understand here. Let's do one more exercise.

$(function () {)

$(".tc-demo-container") Css ("background-color", "yellow")

})

The answer to how to write its type file is as follows

Interface jQueryIntance {

Css: (paramA: string, paramB: string) = > jQueryIntance

}

Declare function $(params: string): jQueryIntance

This time, we separate the type out and define it as an interface, and there is a property named css on the interface, its value is a function, it has two parameters, the type of the parameter is a string, and in fact, this function has a return value, we know that its return value is a jquery object.

Interface rewriting

Seeing the exercise above, did you find another way to write a description file that can be defined using an interface?

/ / interface rewriting

Interface jQueryIntance {

Css: (paramA: string, paramB: string) = > jQueryIntance

Append: (paramA: string) = > jQueryIntance

}

Declare const $: jQueryIntance

Define global object

The above two kinds are actually introducing the definition function, so how to define the object, or take jQuey as an example, we all know that when we use $, we actually execute the method new $.fn.init inside jQuery, so how to define this?

/ / to be defined

New $.fn.init

/ / to ensure that there is no conflict, you can use namespace to frame

Declare namespace ${

Namespace fn {

Class init {}

}

}

To take another example from a real project, for example, we wrote a utility function util similar to loadsh, and we mounted it to the window object in the following way.

Util.add ()

/ / or

Window.util.add ()

At this point, typescript will report an error, and it will report that util does not exist on window, so we need to define its type in the description file, which we can write

Declare interface Window {

Util: {

Add: () = > void

}

}

Defines a Window (note that Window is capitalized), on which there is an object of util, which has an add method, which has no parameters and no return value

Modular file declaration

In fact, after the rise of modern front-end development, especially Vue and React, large-scale projects are almost modular, and the syntax used is ES6's module syntax, so take jquery as an example.

/ / using jquery in modern frameworks

Import $from "jquery"

I think it is more like this way of writing now, if it is written this way, then there is no installation of types, then in. How to describe and define types in d.ts

Let's just look at an example, the code is still the above code, integrate it.

/ / Code

Import $from "jquery"

$("body") Append ("oliver")

New $.fn.init ()

Correspondingly, in. This is what should be written in d.ts:

Declare module "jquery" {

Function $(params: string): {

Append: (params: string) = > {}

}

Namespace ${

Namespace fn {

Class init {}

}

}

Export = $

}

We use keywords: declare describes a type, the type is modle, and the variable name is jquery. Note: the jquery after module is the same as the jquery after import, and the content is basically the same as before. The difference lies in two points:

The keyword declare is not needed internally, because if it is described on the outside, it will not be needed on the inside.

What is defined in it must be exposed if it is to be used for external use. The way of exposure is export.

The above is about the content of this article on "how to use jQuery in typescript". I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report