This is the 23rd day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021
Examples of TypeScript
TypeScript type definition files (TypeScript)Copy the code
Function overloading
/ / 1
// demo.ts
$(function () {$('body').html('hello');
})
// jquery.d.ts
interface JqueryInstance {
html: (html: string) = > JqueryInstance
}
interface JQuery {
(param: () = > void) :void;
(param: string): JqueryInstance;
}
declare var $: JQuery;
Copy the code
The previous article implemented function overloading by defining a function of the same name. Here, function overloading is reimplemented using the syntax of the interface interface.
Type definitions for objects and classes
/ / 2
// demo.ts
$(function () {
new $.fn.init();
})
Copy the code
New a class or constructor like $.fn.init(). The editor promotes the error that fn does not exist because TypeScript does not know that fn is included under $. So how do you write a type definition file like this?
The previous article explained how to type global functions, and I continue here with how to type objects, as well as classes.
/ / 3
// jquery.d.ts
declare function $(param: () => void) :void;
declare function $(param: string) :JqueryInstance;
declare namespace $ {
namespace fn {
class init {}}}Copy the code
Build the $object with namespace, because the fn below $is also an object, so use namespace nesting. The init constructor is defined using class.
Modular type definition files
Instead of using CDN to import library files, use modular import method, such as NPM to install JQuery package. Error: Jquery module not found when importing $from ‘jquery’
/ / 4
// demo.ts
import $ from 'jquery'
// jquery.d.ts
declare module 'jquery' {
interface JqueryInstance {
html: (html: string) = > JqueryInstance
}
function $(param: () => void) :void;
function $(param: string) :JqueryInstance;
namespace $ {
namespace fn {
class init {}}}export = $;
}
Copy the code
Example 4: Using ES6 modularization to define a module as jquery and put the function-overloaded code in the object, equivalent to using a mixed definition.
1. Do not use the declare keyword in the module. 2. Remember to export $at last.
Declare file syntax summary
The syntax of the declaration file includes: Declare VAR Declare global variables DECLARE Function Declare global methods DECLARE Class Declare global classes DECLARE enum Declare global enumerated types DECLARE Namespace Declare (with child attributes) global objects Interface and type Declare global types export Export variables export Namespace Objects with child attributes Export Default ES6 default export export = CommonJS Export module export As Namespace UMD library declares global variables, UMD fixed syntax. Declare Global Extension Global variable Declare Module Extension module ///
Finish this! If this article helps you at all, please give it a thumbs up.