全局类型
变量
declare var aaa: number;
函数
declare function getName(id: number | string): string;
interface声明函数
declare interface Get {
(id: string): string,
(name: string, age: number): string
}
declare var get: Get;
class
declare class Person {
static maxAge: number;
static getMaxAge(): number;
constructor(name: string, age: number);
getName(id: string): string;
}
对象
对象上面可能有变量,可能有函数、类
declare namespace OOO {
var aaa: number | string;
function getName(id: number | string): string;
class Person {
static max Age: number;
static getMaxAge(): number;
constructor(name: string, age: number);
getName(id: string): string;
}
}
混合类型
既是函数又是对象
declare function $2(s: string): void
declare namespace $2 {
let aaa: number;
}
既是函数,又是类,又是对象
declare function getNum(w: number): number;
declare function getNum(w: string): number;
declare class Person {
constructor(name: string, age: number);
constructor(id: number);
name: string;
age: number;
getName(): string;
static a: string;
static staticA():number;
}
declare namespace People{
export var abc: number;
}
模块化的全局变量
import { Request, Response } from 'express';
// 由于当前的d.ts文件使用了import/export语法,就不会把declare var xxx:yyy当成全局变量了,需要改为
declare global {
var req: Request;
var res: Response;
namespace OOO {
var a: number;
}
}
模块化(CommonJS)
declare module "abcd"{
export let a: number;
export function b(): number;
export namespace s {
let cd: string
}
}
ES6的模块化方式(import export)
declare var aaa: number;
export { aaa };
UMD
有一种代码,既可以通过全局变量访问到,也可以通过require的方式访问到。
declare namespace UUU {
let a: number
}
console.log(UUU.a);
declare module "UUU"{
export = UUU;
}
let u = require("UUU");
console.log(UUU.a);