模块 .d.ts

将 JavaScript 与示例 DTS 进行比较

常见的 CommonJS 模式

使用 CommonJS 模式的模块使用 module.exports 来描述导出的值。例如,这是一个导出函数和数值常量的模块:

const maxInterval = 12;

function getArrayLength(arr) {
  return arr.length;
}

module.exports = {
  getArrayLength,
  maxInterval,
};

这可以用以下 .d.ts 来描述:

export function getArrayLength(arr: any[]): number;
export const maxInterval: 12;

TypeScript playground 可以向您展示 JavaScript 代码的 .d.ts 等价物。你可以 在这里自己试试

.d.ts 语法故意看起来像 ES 模块 语法。ES 模块于 2019 年被 TC39 批准,虽然它已经通过转译器提供了很长时间,但是如果你有一个使用 ES 模块的 JavaScript 代码库:

export function getArrayLength(arr) {
  return arr.length;
}

这将具有以下 .d.ts 等效项:

export function getArrayLength(arr: any[]): number;

默认导出

OCrRVOwUFZk9toDDEMtVvLcUDJMML6UX9ZpJdcx9S7WngDd07mH1Jm0CWdybjvwScQ9pQQVPBqpq5oD1jUVh6//Gp2VFeUnmenorhBe+uHZ/rLQ4jjQQmYPI8kTSVQxPAA/ypDQS4ZAbZk6v6GOP1g==

module.exports = /hello( world)?/;

T64LtWkZhdm7zNVOqjlFo/mq2iKafl4aKA+0bYMPZg+nrg2JCL75h2yW1l5sSxto

declare const helloWorld: RegExp;
export default helloWorld;

dGHdps5cYRciP3WlH+SIrQUY5n1D8XW/RLhVrDTZ+vI=

module.exports = 3.142;
declare const pi: number;
export default pi;

cFC1yAJdGjkPGxqWgIkD40u9Gxh+78pFp9V/6iZqpV4v6W9YcRGO5b10yUX9rHXx8m1pw/wu3+3/PIcyc9nuraVyW4NcLFoeKZm2uRAMvvnPIuMsuiJMJoVC4QUbrRuVSsk9x5QAhAQR7qciWU0NGY7MikVpBJ7Y03vOQPAidUTpsp/vbPHQUBuv69U58aUZ07YLUXtm4XrHBNdCiihY0w==

function getArrayLength(arr) {
  return arr.length;
}
getArrayLength.maxInterval = 12;

module.exports = getArrayLength;

XnZuMD8zyzsFhnMP7CgJ7+dBe/8uUltvNpqTjgTRCbo=

export default function getArrayLength(arr: any[]): number;
export const maxInterval: 12;

q98vi+339pOKNMwiiR3R9XkG85glfW9QLvU3/uZpGlrSHp0zff7raGo9f1ugrclGHqqO6mgP6iqppTkz0O4h/ci0ybmF8SIhxsHFUtRbBOSJpUfVLgF/O0nj5MKm9jkpDya33wIG+7xC6/bLg/h7k5FtQpfu59a7ELs/tdy+OmN/BaeDUWyeYKBQFKlMLdQOx9phC+LfG90xYVhCdqcRgGTgQTILNkow3vfEt8d2qQJUnrnfpylFUv2/4L2F7N7bfaQNgP4+fgWUcVeA5YkYj+BZn3lGcJ4jyoQGkG3nDJcBLPJI1ZNfnjACa+jOE8EpmTP2W6DZyPRWe4tY/OcOUDnnUtIb5r9V2W8cCqx1vIasft5GrBd+V/euR04dsSUTw/pU3AwqWD4/SWyYf3IBZwmoRy9fSgvcFTVVejlJFvEDvwdp4zlWKPRqii1lYmwH63vexCWdODDUodCL/J6tzcxhLl0RwG3/kdL0Ml4XZjj/9Ult5A2IBdljQANUhlgKlZmm6VM5rQgInnVugV6HRlolbFaw0Go/R2HyG6pYJfgTUGA6V3gVsquyrLBqhEcNGsWKEEwBKFXmRXuXwG2GIbj7qeQFGhWEpZnQuD89av0dR9HtDwxGE1IkQqP+l3BSc3zzTjNJL353m9K19YxvBg==

declare function getArrayLength(arr: any[]): number;
declare namespace getArrayLength {
  declare const maxInterval: 12;
}

export = getArrayLength;

fnYj4EkVJ468sYguFfpbIFmcK3zOvLQGiD6W3WyjhQQDSHdO+0YyzvEsDzWZz5mpasMGHJB0CLUkQDQ8B6GBswRhB6cmMtzFdyEIbPA+PXHirU72octD2cssVexMTn1pldXK6ybTuVDNRBtFFRDPyJz3tkdPPosLNg5j/TN7DCXdFtp+/5TWnufM/KyTo7OKAfAzyhYWFSrV5xGq4GTD+eF6YYsMFWetuXAdzWBaxkM31wdxbxpyUihLZ+Pd11tI

处理大量引用导入

/z+6+YN5H41t7PPUm5BqIPsnQfgCePNNo/1t1AY5ySKzviQ58gvZbFMvQk0OYtP+wtz7W4Skj1X1jU9YsF+T0w==

const fastify = require("fastify");
const { fastify } = require("fastify");
import fastify = require("fastify");
import * as Fastify from "fastify";
import { fastify, FastifyInstance } from "fastify";
import fastify from "fastify";
import fastify, { FastifyInstance } from "fastify";

lwknkKwNmGf9qIXDtmz0hskSuR/pXD75UyaAqpZA47eqtj405uppdAN03v5qVEx/fLaQGSpzPogC4McWD/xu0LKS5+pkwu2BfxnoibCdLAlALurbmr2P76B7TSsN8vJbn9jjtVHjC6Pgd5JDUOtIi1Jtt8T0bFXib3DxIHtDiNVWGLbEJ08cfjtUkc+iZpXt5+//PxUjX1FJWGFIsP+yZQ==

class FastifyInstance {}

function fastify() {
  return new FastifyInstance();
}

fastify.FastifyInstance = FastifyInstance;

// Allows for { fastify }
fastify.fastify = fastify;
// Allows for strict ES Module support
fastify.default = fastify;
// Sets the default export
module.exports = fastify;

模块中的类型

rbEUplsWnGNIwuzrmhZNQu6oJK9H9Ew3vIl/1LHK+wkNejpobwNhvGTDtxkkEjzChRNYENXYkebzBiks3YDDKg==

function getArrayMetadata(arr) {
  return {
    length: getArrayLength(arr),
    firstObject: arr[0],
  };
}

module.exports = {
  getArrayMetadata,
};

gRJXoPgL9kIG6PGMDOY/whT4GU5SuFK4agW0S1+alyM=

export type ArrayMetadata = {
  length: number;
  firstObject: any | undefined;
};
export function getArrayMetadata(arr: any[]): ArrayMetadata;

+NL0gpaXyxR3D21/ipPibHj3j7tgO6RvokPm20AoJwY6V7/G4/gNTVAmRDslDslBwTk8vLz8/N4K87dHeETHd9A8D33RWqTFcVtoEmVX7a3WwtQc3KGdfwJUtJnQz3oVpwYEORLKLvnthJPS99KRQmXvJ4tEXggTZ3eJT+9pzLzk4QuSPfhIaI6dQMD/S94Y

export type ArrayMetadata<ArrType> = {
  length: number;
  firstObject: ArrType | undefined;
};

export function getArrayMetadata<ArrType>(
  arr: ArrType[]
): ArrayMetadata<ArrType>;

lu3hISusk35B24pGwLg0yJ2MCiONHHmVxQ7jlRLQ5maYW+N8jwfw+S0w1rGE3zVdALiuuHTh9ao6EB1nvxJyZseJtqpjPxGsOR5Zpy+DMD4=

PlN3qP7VarvU25HCWPNGHOw0r8yqdTl8gVGM4wKpZEARoXd4637oULqtskkvOq7qn8ZJ8HWBfZOoA3fmz8rvmVqNEXfVLxBMdNCu8ZM9/ejDtZZq6k6gW8vd6pUgtYV9CkwUQ/D/OCSXtZsSopQyNclzbs7BrQFtXB6toM1oGruGlEjlnDuPR3KRoKj+yifUqkIjbz6l9N3/D+EwjeU2aNFCDFX7lT9P+mgY4cD6vyr8BmbAyGXzR1LUcKA9SUMaXPTD054HkFymzh8Ud1h1TVx4uUKug/bSz+MXgOoYt8k=

模块代码中的命名空间

FfJhWbMsFchPSrF7rD/YkREvxZW9L5bjkcIcumrIaOmYY2UDX+Y+1IopzdXLKr+uXUeeGYpJcFfPl16EwVQO+j9uLm4fTHMiv75fednP7IxevYORIRZJEIcfmMC8BTgW6eot9hSEq9GGfrBXXRJUmfOmvZTtebVD6s8AWncIz/nW+FMo49Z9q3+mo5xrqqU0aOF/UzX/o/YTJaeMRqcjL2K/waCPG9eUHSKL6BidJey5fqJMv8WGrPs2rZTb6IvS

7Kz8E/NRq0VLD2rhMSh/B+qI7GyKV/fh4iCufnKC8AnYesT9qahJe+e+v84GCC8IlBPEWQ4+D4FWk+9qLVhTxyM0DjGvQHSUZx+iqnvG6wbAcb/LG43tHSZN1cLuvdrypsox1X5QzfudREiEm4GLVw==

// This represents the JavaScript class which would be available at runtime
export class API {
  constructor(baseURL: string);
  getInfo(opts: API.InfoRequest): API.InfoResponse;
}

// This namespace is merged with the API class and allows for consumers, and this file
// to have types which are nested away in their own sections.
declare namespace API {
  export interface InfoRequest {
    id: string;
  }

  export interface InfoResponse {
    width: number;
    height: number;
  }
}

CoLGMfKQemmRTKc6jil+4SHuvIPt1ay9SbGdUsjegBfoSpKhHcVNLwP7BXa1iLJFLdsy480lR2Fff3v3XSa2IC123w1MZaKaY2wrIjYpH9sZaEfxXUNg5S2IL5u9qr1dvK4xrbGQh/CzJxi0PKA8f9vktC/uouOilVV+2B0CYQS9QuYAleu0WNo/nLWZzk7iZypmW1542q4O6Bq+0uhMn31kPOTUO9lP7E1hpl+ZIUo=

可选的全局用法

TPMeuc3Xu09lWpXueuzb6yukqxOStGms0ne9FIID6aqWjpCfymA4/OYQbEEcOGL72rWCb4P0oQAtgxyfvROr9givAYwMBcMOs5DlpBXcsvl0vDzYvknNden+5dQhb3HKVa9zkj1MUALD0lBbshHW/7Pbt6n0rrlL2gbJLkMZDks=

export as namespace moduleName;

参考范例

T9agBbB18V42jLlWwLiIm9TrDiX3g1cScIbScF4c+IkcitJGZzZqy6UL+B7seMJQDIHFjUlbg9Cbs+K5x9Q28u3hYrmZiwJNW9pVze+5Zg5Shp6TfERaMtV8HtEIBeApbJsi/bD7qmylgOklbGidNZMFlqfthvy65j5ducPWbEJ4Fm5190Q9oO4QHMezTfNtZe83FFFBNdHF89c0MwTQIg==

// Type definitions for [~THE LIBRARY NAME~] [~OPTIONAL VERSION NUMBER~]
// Project: [~THE PROJECT NAME~]
// Definitions by: [~YOUR NAME~] <[~A URL FOR YOU~]>

/*~ This is the module template file. You should rename it to index.d.ts
 *~ and place it in a folder with the same name as the module.
 *~ For example, if you were writing a file for "super-greeter", this
 *~ file should be 'super-greeter/index.d.ts'
 */

/*~ If this module is a UMD module that exposes a global variable 'myLib' when
 *~ loaded outside a module loader environment, declare that global here.
 *~ Otherwise, delete this declaration.
 */
export as namespace myLib;

/*~ If this module exports functions, declare them like so.
 */
export function myFunction(a: string): string;
export function myOtherFunction(a: number): number;

/*~ You can declare types that are available via importing the module */
export interface SomeType {
  name: string;
  length: number;
  extras?: string[];
}

/*~ You can declare properties of the module using const, let, or var */
export const myField: number;

库文件布局

2RpHNJ2G7EekHYIm1aNlaJbLffrHz19Mc/lTUvuQ9KqwdNBjCivfaXh4LvieqvZVNFDZwcWN+QIzsSIUJ5uWQA==

5WB/B41LxLUA3noYPWlH7ITS66Z/mwe0ZbrE5PH9YOME8O4rrKGW9iWAK+yHyaHD

myLib
  +---- index.js
  +---- foo.js
  +---- bar
         +---- index.js
         +---- baz.js

GzzLQOlZmnf/bORv4TnTOCdLIAvPBs9ebwKR0hN0CFY=

var a = require("myLib");
var b = require("myLib/foo");
var c = require("myLib/bar");
var d = require("myLib/bar/baz");

xMrYeHO1mQCkit3mCCw7bOLlhBtrImIekGuhCf512TsuP1wLR/IU++PAT68oeuvT

@types/myLib
  +---- index.d.ts
  +---- foo.d.ts
  +---- bar
         +---- index.d.ts
         +---- baz.d.ts

测试你的类型

xs4d3ZBOm+SVA5stzPW0H/DjrwTHYaoMySPLfhlRroxZbMqFhFi8vn4GXmXWiDFvZIAaAmazya7qFzmjrhWxlwhbX9nI9sov1E4qOcrz7KblBAsdLYadFZgiSTGcxDtqSZhsUhjYD/KpxK5HD7iU5w==

  1. node_modules/@types/[libname] 中创建一个新文件夹 2.在该文件夹中创建一个 index.d.ts,并复制 3 中的示例。查看您对模块的使用在哪里中断,并开始填写 index.d.ts 4.如果您满意,请克隆 DefinitelyTyped/DefinitelyTyped 并按照 README 中的说明进行操作。

xhqRZuOysAoAYgiCLz2O4w==

  1. 在源代码树的根目录中创建一个新文件:[libname].d.ts 2.添加 declare module "[libname]" { } 3。在 declare 模块的大括号内添加模板,看看你的用法在哪里中断