声明文件(.d.ts)用于为JavaScript库提供类型信息。它只包含类型声明,不包含实现代码。
// myLib.d.ts
declare const myLib: {
version: string;
init(config: object): void;
};
declare function greet(name: string): string;
declare class Calculator {
add(a: number, b: number): number;
subtract(a: number, b: number): number;
}
// lodash.d.ts
declare module "lodash" {
export function chunk(array: T[], size: number): T[][];
export function compact(array: T[]): T[];
export function concat(...arrays: T[][]): T[];
}
// 使用
import { chunk } from "lodash";
const result = chunk([1, 2, 3, 4], 2);
// global.d.ts
declare global {
interface Window {
myCustomProperty: string;
}
var MY_GLOBAL_VAR: string;
function myGlobalFunction(): void;
}
export {}; // 使文件成为模块
// jquery.d.ts
declare namespace jQuery {
function ajax(url: string, settings?: any): void;
namespace fn {
function extend(object: any): void;
}
}
declare var $: typeof jQuery;
// math.d.ts
export as namespace math;
export function add(a: number, b: number): number;
export function subtract(a: number, b: number): number;
// 可以作为全局变量使用
//
// math.add(1, 2);
// 也可以作为模块导入
// import { add } from "math";
DefinitelyTyped是一个社区维护的类型声明仓库:
# 安装类型声明
npm install --save-dev @types/node
npm install --save-dev @types/express
npm install --save-dev @types/react
# tsconfig.json
{
"compilerOptions": {
"types": ["node", "express"]
}
}
// 接口合并
interface Box {
height: number;
width: number;
}
interface Box {
scale: number;
}
let box: Box = { height: 5, width: 6, scale: 10 };
// 命名空间合并
namespace Animals {
export class Zebra {}
}
namespace Animals {
export interface Legged {
numberOfLegs: number;
}
export class Dog {}
}
// observable.d.ts
export class Observable {
// ...
}
// map.d.ts
import { Observable } from "./observable";
declare module "./observable" {
interface Observable {
map(f: (x: T) => U): Observable;
}
}
// 现在Observable有map方法了
///
///
///
// 使用声明的类型
const value: MyCustomType = {};
// myLib.js
function createGreeting(name) {
return "Hello, " + name;
}
module.exports = {
createGreeting: createGreeting,
version: "1.0.0"
};
// myLib.d.ts
export function createGreeting(name: string): string;
export const version: string;
// api.d.ts
declare namespace API {
interface RequestConfig {
url: string;
method?: "GET" | "POST" | "PUT" | "DELETE";
headers?: Record;
data?: any;
}
interface Response {
data: T;
status: number;
statusText: string;
}
function request(config: RequestConfig): Promise>;
}
// 使用
API.request({
url: "/api/users/1",
method: "GET"
}).then(response => {
console.log(response.data.name);
});
// utils.d.ts
type IsArray = T extends any[] ? true : false;
type Flatten = T extends Array ? U : T;
type ReturnType = T extends (...args: any[]) => infer R ? R : any;
// package.json
{
"name": "my-library",
"version": "1.0.0",
"main": "dist/index.js",
"types": "dist/index.d.ts", // 指向声明文件
"files": [
"dist"
]
}
// tsconfig.json
{
"compilerOptions": {
"declaration": true, // 生成声明文件
"declarationMap": true, // 生成声明文件的source map
"outDir": "./dist"
}
}