Often, the community has done the usual declaration documents for us. Share this as a note, but also learn how to write when a third party library is not available. Before you do anything, analyze the scenario:
The global variable
- The simplest and most direct, through the tag
<script>
Import and inject global variablesxxx
; npm install @types/xxx --save-dev
Installation, no configuration allowed;- Declaration file
xxx.d.ts
Store current projects, suggestions and others*.ts
All stored in SRC directory (not valid, can be checkedtsconfig.json
In theFile, include, and exclude
Etc configuration);
Declarative statements | meaning | For example, |
---|---|---|
declare var ,declare const ,declare let |
Declare global variables | declareVar.ts |
declare function |
Declare global methods | declareFunction.ts |
declare class |
Declaring a global class | declareClass.ts |
declare enum |
Declare a global enumeration type | declareEnum.ts |
declare namespace |
Declare global objects | declareNamespace.ts |
interface ,type |
Declaring global types | DeclareInterface. Ts and declareType. Ts |
declare var
,declare const
,declare let
// jQuery2.d.ts
declare const jQuery2: (selector: string) = > any;
Copy the code
// declareVar2.ts
jQuery2('#root');
Copy the code
declare function
// declareFunction.d.ts
declare function declareFunc(selector: string) :any;
Copy the code
// declareFunction.ts
declareFunc('#root');
Copy the code
declare class
// declareClass.d.ts
declare class DeclareClass {
name: string;
constructor(name: string);
showName(): string;
showName2() {
return I was `${this.name}`; }}/ / 0.1.3 declareClass. Which s: 5:17 - error TS1183: An implementation always be declared in ambient contexts.
// 5 showName2() {
Copy the code
// declareClass.ts
let declareClass = new DeclareClass('class');
Copy the code
Declare class defines only types, not implementations. (In this example, showName2 is an implementation, so an error is reported.)
declare enum
// declareEnum.d.ts
declare enum DeclareEnum {
man,
woman
}
Copy the code
// declareEnum.d.ts
let person = [ DeclareEnum.woman, DeclareEnum.man ];
Copy the code
declare namespace
Namespace first seen, is ts early to solve the modular built keyword, as the name implies is the meaning of namespace.
ES6 uses the module as well. Because TS is compatible with ES6, we have to change the module to namespace.
Not recommended: With the introduction of ES6, TS does not recommend namespaces to solve the modularity problem, instead recommending the use of ES6 modularity solution (TS is very inclusive, all for the convenience of the programmer).
Understand how it works: Although namespace is deprecated, declare namespace is still commonly used, representing an object of a global variable and therefore having child properties.
// declareNamespace.d.ts
declare namespace declareNamespace {
const name: string;
function showName(name: string) :void;
class Gender {
showGender(gender: string) :void;
}
enum Direction { up, right, down, left }
namespace ns {
function showNs(name: string) :void; }}Copy the code
// declareNamespace.ts
declareNamespace.showName('declareNamespace');
declareNamespace.ns.showNs('ns');
Copy the code
Note: You can continue to embed declared objects in declared objects.
interface
和 type
// interface.d.ts
interfaceOptions { position? :'TOP' | 'BOTTOM'; data? :any;
}
declare namespace modal {
function open(title: string, options? : Options) :void;
}
Copy the code
// interface.ts
let options: Options = {
position: 'top',
data: {
width: 200
}
}
modal.open('new', options);
Copy the code
There is nothing wrong with interface, but it is exposed in a global type, so it is best stored in a namespace
// interface2.d.ts
declare namespace modal {
interfaceOptions { position? :'top' | 'bottom'; data? :any;
}
function open(title: string, options? : Options) :void;
}
Copy the code
// interface2.ts
let options: modal.Options = {
position: 'top',
data: {
width: 200
}
}
modal.open('new', options);
Copy the code
NPM package
Import XXX from ‘XXX’ according to ES6 module specification. Know how to import NPM packages, and also know how to create NPM packages.
Declare the file storage location
Bundled with the NPM package (NPM publisher also provides the declaration file, conscience Publisher)
The scenario is that when taking over a project, one is to check the types in package.json for its NPM package, and the other is to check whether there are XXX /index.d.ts declaration files. For your own convenience and the convenience of others, bind the declaration file to the NPM package (if you later publish the NPM package yourself).
In the community@types
(Not bundled with the NPM package, distributed by others)
NPM install @types/ XXX -s (NPM install @types/ XXX -s) is used to check whether @types has a declaration file. But only to @types).
If you can’t find the declaration file in either case, you’ll have to write your own declaration file.
One is created on node_modules/@types/ XXX /index.d.ts, which doesn’t require extra configuration (benefit), but node_modules are unstable, Node_modules is not recommended because the node_modules directory does not publish to the repository, cannot be versioning back, has deletion risks, and can be used by multiple teams. Second, create the types directory to store the declaration files written by yourself, such as @types/ XXX /index.d.ts. At the moment, tsconfig.json is needed to successfully avoid the problems caused by the first method.
The table of contents is as follows (most simple and refreshing but useful)
Project ├ ─ ─ the SRC | └ ─ ─ but ts ├ ─ ─ types | └ ─ ─ XXX | └ ─ ─ the index, which s └ ─ ─ tsconfig. JsonCopy the code
tsconfig.json
content
{
"compilerOptions": {
"module": "commonjs"."baseUrl": ". /"."paths": {
"*": ["types/*"]}}}Copy the code
Declaration file syntax
grammar | meaning | The sample |
---|---|---|
export | Export variables | types/export/index.d.ts 和 0.1.3 / export. Ts |
export namespace | Exporting objects (including child attributes) | types/export/index.d.ts 和 0.1.3 / export. Ts |
export default | Exporting defaults (ES6) (recommended) | types/exportDefault/*.d.ts 和 0.1.3 / exportDefault. Ts |
export = commonjs | Exporting modules (not recommended) |
export
Export variables
The NPM package declaration file differs from the global variable declaration file mentioned earlier.
- Do not use
declare
When you declare a global variable, you just declare a common variable (local variable); - Used in declaration files
export
Export; - Use file
import
Import and use, same as ES6 (no learning cost);
Here’s how to create your own declaration file. It’s recommended to write it in the Types directory, as well as the rest.
// types/export/index.d.ts
export const name: string;
export function showName() :string;
export class Star {
constructor(name: string);
say(): string;
}
export enum Gender {
woman,
man
}
export interfaceOptions { position? :'TOP' | 'BOTTOM'; data? :any;
}
export namespace declareNamespace {
const name: string;
namespace ns {
function showNs(name: string) :string; }}Copy the code
/ / 0.1.3 / export. Ts
import { name, showName, Star, Gender, Options, declareNamespace } from '.. /types/export';
console.log(name);
let myName = showName();
let newStar = new Star('pr');
let gender = [Gender.woman, Gender.man];
let options: Options = {
position: 'TOP',
data: { name: 'pr', age: 18}}console.log(declareNamespace.name);
declareNamespace.ns.showNs('ns');
Copy the code
export default
Exporting defaults (ES6)
Export default Both ES6 and Typescript export directly by default. Function, class, and interface are exported directly in Typescript.
// types/exportDefault/function.d.ts
export default function showName() :string;
Copy the code
// types/exportDefault/class.d.ts
export default class Star {
constructor(name: string);
say(): string;
}
Copy the code
// types/exportDefault/interface.d.ts
export default interfaceOptions { position? :'TOP' | 'BOTTOM'; data? :any;
}
Copy the code
// types/exportDefault/enum.d.ts
declare enum Gender {
woman,
man
}
export default Gender;
Copy the code
// types/exportDefault/namespace.d.ts
declare namespace declareNamespace {
const name: string;
namespace ns {
function showNs(name: string) :string; }}export default declareNamespace;
Copy the code
export =
Export module
In the CommonJS specification, exporting a module can
// Export the whole
module.exports = xxx;
// Export a single
exports.xxx = xxx;
Copy the code
In Typescript, there are several ways to import commonJS module exports
// Import the whole
const xxx = require('xxx');
import * as xxx from 'xxx';
import xxx = require('xxx');
// Import a single
const fn = require('xxx').fn;
import { fn } from 'xxx';
import fn = xxx.fn;
Copy the code
Note: the import… Both require and export = are syntaxes created by Typescript to be compatible with the AMD and CommonJS specifications and are not recommended because they are not commonly used. Instead, the ES6 standard export Default and Export are recommended (everyone uses them).
UMD library
Universal Module Definition, UMD libraries are those that can be imported through the
// types/umd/index.d.ts
export as namespace umd;
export default umd;
// export = umd;
declare function umd() :string;
declare namespace umd {
let ns: string;
function showNs(ns: number) :string;
}
Copy the code
/ / 0.1.3 umd. Ts
import umd from '.. /types/umd';
umd();
umd.ns = '18';
umd.showNs(18);
Copy the code
Extend global variable
This code Github
You can…
Previous: Typescript declaration files
Next: Typescript collation
Contents: A primer to Typescript’s short book