- Notifications
You must be signed in to change notification settings - Fork1
The repository for high quality TypeScript type definitions.
License
javascript-obfuscator/DefinitelyTyped
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
The repository forhigh quality TypeScript type definitions.
You can also read this README inSpanish,Korean,Russian,Chinese,Portuguese,ItalianandJapanese!
Link toAdmin manual
This section tracks the health of the repository and publishing process.It may be helpful for contributors experiencing any issues with their PRs and packages.
- Most recent buildtype-checked/linted cleanly:
- All packages are type-checking/linting cleanly on typescript@next:
- All packages are beingpublished to npm in under an hour and a half:
- typescript-bot has been active on Definitely Typed
- Currentinfrastructure status updates
If anything here seems wrong, or any of the above are failing, please let us know inthe Definitely Typed channel on the TypeScript Community Discord server.
See theTypeScript handbook.
This is the preferred method. For example:
npm install --save-dev @types/node
The types should then be automatically included by the compiler.You may need to add atypes reference if you're not using modules:
/// <reference types="node" />See more in thehandbook.
For an npm package "foo", typings for it will be at "@types/foo".If you can't find your package, look for it onTypeSearch.
If you still can't find it, check if itbundles its own typings.This is usually provided in a"types" or"typings" field in thepackage.json,or just look for any ".d.ts" files in the package and manually include them with a/// <reference path="" />.
Definitely Typed only tests packages on versions of TypeScript that are less than 2 years old.
Currently versions 3.8 and above are tested...
If you're using TypeScript 2.0 to 3.7, you can still try installing@types packages — the majority of packages don't use fancy new TypeScript features.But there's no guarantee that they'll work.Here is the support window:
@types packages have tags for versions of TypeScript that they explicitly support, so you can usually get older versions of packages that predate the 2-year window.For example, if you runnpm dist-tags @types/react, you'll see that TypeScript 2.5 can use types for react@16.0, whereas TypeScript 2.6 and 2.7 can use types for react@16.4:
| Tag | Version |
|---|---|
| latest | 16.9.23 |
| ts2.0 | 15.0.1 |
| ... | ... |
| ts2.5 | 16.0.36 |
| ts2.6 | 16.4.7 |
| ts2.7 | 16.4.7 |
| ... | ... |
- Manually download from the
masterbranch of this repository and place them in your project Typings(use preferred alternatives, typings is deprecated)NuGet(use preferred alternatives, nuget DT type publishing has been turned off)
You may need to add manualreferences.
Definitely Typed only works because of contributions by users like you!
Before you share your improvement with the world, use the types yourself by creating atypename.d.ts file in your project and filling out its exports:
declare module"libname"{// Types inside hereexportfunctionhelloWorldMessage():string}
You can edit the types directly innode_modules/@types/foo/index.d.ts to validate your changes, then bring the changes to this repo with the steps below.
Alternatively, you can usemodule augmentation to extend existing types from the DT module or use thedeclare module technique above which will override the version innode_modules.
Add to yourtsconfig.json:
"baseUrl":"types","typeRoots": ["types"],
Createtypes/foo/index.d.ts containing declarations for the module "foo".You should now be able to import from"foo" in your code and it will route to the new type definition.Then buildand run the code to make sure your type definition actually corresponds to what happens at runtime.
Once you've tested your definitions with real code, make aPRthen follow the instructions toedit an existing package orcreate a new package.
Once you've tested your package, you can share it on Definitely Typed.
First,fork this repository,clone it, installnode, and runnpm install. If usingnpm v7 you need to add the--legacy-peer-deps flag to the command.
We use a bot to let a large number of pull requests to DefinitelyTyped be handled entirely in a self-service manner. You can read more aboutwhy and how here. Here is a handy reference showing the life-cycle of a pull request to DT:
You can clone the entire repositoryas per usual, but it's large and includes a massive directory of type packages.
You can clone the entire repositoryas per usual, but it's large and includes a massive directory of type packages. This will take some time to clone and may be unnecessarily unwieldy.
For a more manageable clone that includesonly the type packages relevant to you, you can use git'ssparse-checkout,--filter, and--depth features. This will reduce clone time and improve git performance.
⚠️ This requires minimumgit version 2.27.0, which is likely newer than the default on most machines. More complicated procedures are available in older versions, but not covered by this guide.
git clone --sparse --filter=blob:none --depth=1 <forkedUrl>--sparseinitializes the sparse-checkout file so the working directory starts with only the files in the root of the repository.--filter=blob:nonewill exclude files, fetching them only as needed.--depth=1will further improve clone speed by truncating commit history, but it may cause issues as summarizedhere.
git sparse-checkout add types/<type> types/<dependency-type> ...
cd types/<package to edit>- Make changes. Remember toedit tests.If you make breaking changes, do not forget toupdate a major version.
- Run
npm test <package to test>.
When you make a PR to edit an existing package,dt-bot should @-mention previous authors.If it doesn't, you can do so yourself in the comment associated with the PR.
If you are the library author and your package is written in TypeScript,bundle the autogenerated declaration files in your package instead of publishing to Definitely Typed.
If you are adding typings for an npm package, create a directory with the same name.If the package you are adding typings for is not on npm, make sure the name you choose for it does not conflict with the name of a package on npm.(You can usenpm info <my-package> to check for the existence of the<my-package> package.)
Your package should have this structure:
| File | Purpose |
|---|---|
index.d.ts | This contains the typings for the package. |
<my-package>-tests.ts | This contains sample code which tests the typings. This code doesnot run, but it is type-checked. |
tsconfig.json | This allows you to runtsc within the package. |
tslint.json | Enables linting. |
Generate these by runningnpx dts-gen --dt --name <my-package> --template module if you have npm ≥ 5.2.0,npm install -g dts-gen anddts-gen --dt --name <my-package> --template module otherwise.See all options atdts-gen.
If you have.d.ts files besidesindex.d.ts, make sure that they are referenced either inindex.d.ts or the tests.
Definitely Typed members routinely monitor for new PRs, though keep in mind that the number of other PRs may slow things down.
For a good example package, seebase64-js.
When a packagebundles its own types, types should be removed from Definitely Typed to avoid confusion.
You can remove it by runningnpm run not-needed -- <typingsPackageName> <asOfVersion> [<libraryName>].
<typingsPackageName>: This is the name of the directory to delete.<asOfVersion>: A stub will be published to@types/<typingsPackageName>with this version. Should be higher than any currently published version, and should be a version of<libraryName>on npm.<libraryName>: Name of npm package that replaces the Definitely Typed types. Usually this is identical to<typingsPackageName>, in which case you can omit it.
Any other packages in Definitely Typed that referenced the deleted package should be updated to reference the bundled types.You can get this list by looking at the errors fromnpm run test-all.To fix the errors,add apackage.json with"dependencies": { "<libraryName>": "x.y.z" }.For example:
{"private":true,"dependencies": {"<libraryName>":"^2.6.0" }}When you add apackage.json to dependents of<libraryName>, you will also need to open a PR to add<libraryName>to allowedPackageJsonDependencies.txt in DefinitelyTyped-tools.
If a package was never on Definitely Typed, it does not need to be added tonotNeededPackages.json.
Test your changes by runningnpm test <package to test> where<package to test> is the name of your package.
This script usesdtslint to run the TypeScript compiler against your dts files.
Once you have all your changes ready, usenpm run test-all to see how your changes affect other modules.
If you are adding typings for an npm package, create a directory with the same name.If the package you are adding typings for is not on npm, make sure the name you choose for it does not conflict with the name of a package on npm.(You can usenpm info <my-package> to check for the existence of the<my-package> package.)
If a non-npm package conflicts with an existing npm package try adding -browser to the end of the name to get<my-package>-browser.
There should be a<my-package>-tests.ts file, which is considered your test file, along with any*.ts files it imports.If you don't see any test files in the module's folder, create a<my-package>-tests.ts.These files are used to validate the API exported from the*.d.ts files which are shipped as@types/<my-package>.
Changes to the*.d.ts files should include a corresponding*.ts file change which shows the API being used, so that someone doesn't accidentally break code you depend on.If you don't see any test files in the module's folder, create a<my-package>-tests.ts
For example, this change to a function in a.d.ts file adding a new param to a function:
index.d.ts:
- export function twoslash(body: string): string+ export function twoslash(body: string, config?: { version: string }): string
<my-package>-tests.ts:
import {twoslash} from "./"// $ExpectType stringconst result = twoslash("//")+ // Handle options param+ const resultWithOptions = twoslash("//", { version: "3.7" })+ // When the param is incorrect+ // $ExpectError+ const resultWithOptions = twoslash("//", { })If you're wondering where to start with test code, the examples in the README of the module are a great place to start.
You canvalidate your changes withnpm test <package to test> from the root of this repo, which takes changed files into account.
Use$ExpectType to assert that an expression is of a given type, and$ExpectError to assert that a compile error. Examples:
// $ExpectType voidf(1);// $ExpectErrorf("one");
For more details, seedtslint readme.
The linter configuration file,tslint.json should contain{ "extends": "@definitelytyped/dtslint/dt.json" }, and no additional rules.
If for some reason some rule needs to be disabled,disable it for that specific line using// tslint:disable-next-line:[ruleName] — not for the whole package, so that disabling can be reviewed. (There are some legacy lint configs that have additional contents, but these should not happen in new work.)
tsconfig.json should havenoImplicitAny,noImplicitThis,strictNullChecks, andstrictFunctionTypes set totrue.
You may edit thetsconfig.json to add new test files, to add"target": "es6" (needed for async functions), to add to"lib", or to add the"jsx" compiler option.
TL;DR:esModuleInterop andallowSyntheticDefaultImports arenot allowed in yourtsconfig.json.
These options make it possible to write a default import for a CJS export, modeling the built-in interoperability between CJS and ES modules in Node and in some JS bundlers:
// component.d.tsdeclareclassComponent{}// CJS export, modeling `module.exports = Component` in JSexport=Component;// index.d.ts// ESM default import, only allowed under 'esModuleInterop' or 'allowSyntheticDefaultExports'importComponentfrom"./component";Since the compile-time validity of the import in
index.d.tsis dependent upon specific compilation settings, which users of your types do not inherit, using this pattern in DefinitelyTyped would force users to change their own compilation settings, which might be incorrect for their runtime. Instead, you must write a CJS import for a CJS export to ensure widespread, config-independent compatibility:// index.d.ts// CJS import, modeling `const Component = require("./component")` in JSimportComponent= require("./component");
Usually you won't need this.DefinitelyTyped's package publisher creates apackage.json for packages with no dependencies outside Definitely Typed.Apackage.json may be included to specify dependencies that are not other@types packages.Pikaday is a good example.Even if you write your ownpackage.json, you can only specify dependencies; other fields such as"description" are not allowed.You also need to add the dependency tothe list of allowed packages.This list is updated by a human, which gives us the chance to make sure that@types packages don't depend on malicious packages.
In the rare case that an@types package is deleted and removed in favor of types shipped by the source package AND you need to depend on the old, removed@types package, you can add a dependency on an@types package.Be sure to explain this when adding to the list of allowed packages so that the human maintainer knows what is happening.
If a file is neither tested nor referenced inindex.d.ts, add it to a file namedOTHER_FILES.txt. This file is a list of other files that need to be included in the typings package, one file per line.
- First, follow advice from thehandbook.
- Formatting: Use 4 spaces. Prettier is set up on this repo, so you can run
npm run prettier -- --write path/to/package/**/*.ts.When using assertions, add// prettier-ignoreexclusion to mark line(s) of code as excluded from formatting:// prettier-ignoreconstincompleteThemeColorModes:Theme={colors:{modes:{papaya:{// $ExpectError
function sum(nums: number[]): number: UseReadonlyArrayif a function does not write to its parameters.interface Foo { new(): Foo; }:This defines a type of objects that are new-able. You probably wantdeclare class Foo { constructor(); }.const Class: { new(): IClass; }:Prefer to use a class declarationclass Class { constructor(); }instead of a new-able constant.getMeAT<T>(): T:If a type parameter does not appear in the types of any parameters, you don't really have a generic function, you just have a disguised type assertion.Prefer to use a real type assertion, e.g.getMeAT() as number.Example where a type parameter is acceptable:function id<T>(value: T): T;.Example where it is not acceptable:function parseJson<T>(json: string): T;.Exception:new Map<string, number>()is OK.- Using the types
FunctionandObjectis almost never a good idea. In 99% of cases it's possible to specify a more specific type. Examples are(x: number) => numberforfunctions and{ x: number, y: number }for objects. If there is no certainty at all about the type,anyis the right choice, notObject. If the only known fact about the type is that it's some object, use the typeobject, notObjector{ [key: string]: any }. var foo: string | any:Whenanyis used in a union type, the resulting type is stillany. So while thestringportion of this type annotation maylook useful, it in fact offers no additional typechecking over simply usingany.Depending on the intention, acceptable alternatives could beany,string, orstring | object.
TL;DR: do not modify
.github/CODEOWNERS, always modify list of the owners in theindex.d.tsheader
DT has the concept of "Definition Owners" which are people who want to maintain the quality of a particular module's types
- Adding yourself to the list will cause you to be notified (via your GitHub username) whenever someone makes a pull request or issue about the package.
- Your PR reviews will have a higher precedence of importance tothe bot which maintains this repo.
- The DT maintainers are putting trust in the definition owners to ensure a stable eco-system, please don't add yourself lightly.
To Add yourself as a Definition Owner:
- Adding your name to the end of the line, as in
// Definitions by: Alice <https://github.com/alice>, Bob <https://github.com/bob>. - Or if there are more people, it can be multiline
// Definitions by: Alice <https://github.com/alice>// Bob <https://github.com/bob>// Steve <https://github.com/steve>// John <https://github.com/john>
Once a week the Definition Owners are synced to the file.github/CODEOWNERS which is our source of truth.
Themaster branch is automatically published to the@types scope on npm thanks toDefinitelyTyped-tools.
It depends, but most pull requests will be merged within a week.Some PRs can be merged by the owners of a module, and they can be merged much faster.Roughly:
PRs which only change the types of a module, and have corresponding tests changes will be merged much faster
PRs that have been approved by an author listed in the definition's header are usually merged more quickly; PRs for new definitions will take more time as they require more review from maintainers. Each PR is reviewed by a TypeScript or Definitely Typed team member before being merged, so please be patient as human factors may cause delays. Check theNew Pull Request Status Board to see progress as maintainers work through the open PRs.
For changes to very popular modules, e.g. Node/Express/Jest which have many millions of downloads each per week on npm, the requirements for contributions are a bit higher.Changes to these projects can have massive ecosystem effects, and so we treat changes to them with a lot of care.These modules require both a sign-off from a DT maintainer, and enthusiastic support from the module owners. The bar for passing this can be quite high, and often PRs can go stale because it doesn't have a champion.If you're finding that no-one is committing, try to make your PR have a smaller focus.
npm packages should update within a few minutes. If it's been more than an hour, mention the PR number onthe Definitely Typed channel on the TypeScript Community Discord server and the current maintainer will get the correct team member to investigate.
I'm writing a definition that depends on another definition. Should I use<reference types="" /> or an import?
If the module you're referencing is an external module (usesexport), use an import.If the module you're referencing is an ambient module (usesdeclare module, or just declares globals), use<reference types="" />.
Some packages have notslint.json, and sometsconfig.json are missing"noImplicitAny": true,"noImplicitThis": true, or"strictNullChecks": true.
Then they are wrong, and we've not noticed yet. You can help by submitting a pull request to fix them.
No. We've explored trying to make DT's code-formatting consistent before but reached an impasse due to the high activity on the repo. We include formatting settings via a.editorconfig and.prettierrc.json. These are exclusively for tooling in your editor, their settings don't conflict and we don't plan on changing them. Nor do we plan on enforcing a specific style in the repo. We want to keep the barriers to contributions low.
Here are thecurrently requested definitions.
If types are part of a web standard, they should be contributed toTypeScript-DOM-lib-generator so that they can become part of the defaultlib.dom.d.ts.
Some packages, likechai-http, export a function.
Importing this module with an ES6 style import in the formimport * as foo from "foo"; leads to the error:
error TS2497: Module 'foo' resolves to a non-module entity and cannot be imported using this construct
This error can be suppressed by merging the function declaration with an empty namespace of the same name, but this practice is discouraged.This is a commonly citedStack Overflow answer regarding this matter.
It is more appropriate to import the module using theimport foo = require("foo"); syntax.Nevertheless, if you want to use a default import likeimport foo from "foo"; you have two options:
- you can use the
--allowSyntheticDefaultImportscompiler option if your module runtime supports an interop scheme for non-ECMAScript modules, i.e. if default imports work in your environment (e.g. Webpack, SystemJS, esm). - you can use the
--esModuleInteropcompiler option if you want TypeScript to take care of non-ECMAScript interop (since TypeScript 2.7).
Like in the previous question, refer to using either the--allowSyntheticDefaultImportsor--esModuleInteropcompiler options.
Do not change the type definition if it is accurate.For an npm package,export = is accurate ifnode -p 'require("foo")' works to import a module, andexport default is accurate ifnode -p 'require("foo").default' works to import a module.
Then you will have to add a comment to the last line of your definition header (after// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped):// Minimum TypeScript Version: X.Y. This will set the lowest minimum supported version.
However, if your project needs to maintain types that are compatible with, say, 3.7 and aboveat the same time as types that are compatible with 3.6 or below, you will need to use thetypesVersions feature.You can find a detailed explanation of this feature in theofficial TypeScript documentation.
Here's a short example to get you started:
You'll have to add a
package.jsonfile to your package definition, with the following contents:{"private":true,"types":"index","typesVersions": {"<=3.6": {"*": ["ts3.6/*"] } }}Create the sub-directory mentioned in the
typesVersionsfield inside your types directory (ts3.6/in this example).ts3.6/will support TypeScript versions 3.6 and below, so copy the existing types and tests there.You'll need to delete the definition header from
ts3.6/index.d.tssince only the rootindex.d.tsis supposed to have it.Set the
baseUrlandtypeRootsoptions ints3.6/tsconfig.jsonto the correct paths, which should look something like this:{"compilerOptions": {"baseUrl":"../../","typeRoots": ["../../"] }}Back in the root of the package, add the TypeScript 3.7 features you want to use.When people install the package, TypeScript 3.6 and below will start from
ts3.6/index.d.ts, whereas TypeScript 3.7 and above will start fromindex.d.ts.You can look atbluebird for an example.
This may belong inTypeScript-DOM-lib-generator. See the guidelines there.If the standard is still a draft, it belongs here.Use a name beginning withdom- and include a link to the standard as the "Project" link in the header.When it graduates draft mode, we may remove it from Definitely Typed and deprecate the associated@types package.
NOTE: The discussion in this section assumes familiarity withSemantic versioning
Each Definitely Typed package is versioned when published to npm.TheDefinitelyTyped-tools (the tool that publishes@types packages to npm) will set the declaration package's version by using themajor.minor version number listed in the first line of itsindex.d.ts file.For example, here are the first few lines ofNode's type declarations for version10.12.x at the time of writing:
// Type definitions for Node.js 10.12// Project: https://nodejs.org/// Definitions by: Microsoft TypeScript <https://github.com/Microsoft>// Definitely Typed <https://github.com/DefinitelyTyped>// Alberto Schiabel <https://github.com/jkomyno>
Because10.12 is at the end of the first line, the npm version of the@types/node package will also be10.12.x.Note that the first-line comment in theindex.d.ts file should only contain themajor.minor version (e.g.10.12) and should not contain a patch version (e.g.10.12.4).This is because only the major and minor release numbers are aligned between library packages and type declaration packages.The patch release number of the type declaration package (e.g..0 in10.12.0) is initialized to zero by Definitely Typed and is incremented each time a new@types/node package is published to npm for the same major/minor version of the corresponding library.
Sometimes type declaration package versions and library package versions can get out of sync.Below are a few common reasons why, in order of how much they inconvenience users of a library.Only the last case is typically problematic.
- As noted above, the patch version of the type declaration package is unrelated to the library patch version.This allows Definitely Typed to safely update type declarations for the same major/minor version of a library.
- If updating a package for new functionality, don't forget to update the version number to line up with that version of the library.If users make sure versions correspond between JavaScript packages and their respective
@typespackages, thennpm updateshould typically just work. - It's common for type declaration package updates to lag behind library updates because it's often library users, not maintainers, who update Definitely Typed when new library features are released.So there may be a lag of days, weeks, or even months before a helpful community member sends a PR to update the type declaration package for a new library release.If you're impacted by this, you can be the change you want to see in the world and you can be that helpful community member!
❗ If you're updating type declarations for a library, always set themajor.minor version in the first line ofindex.d.ts to match the library version that you're documenting! ❗
If a library is updated to a new major version with breaking changes, how should I update its type declaration package?
Semantic versioning requires that versions with breaking changes must increment the major version number.For example, a library that removes a publicly exported function after its3.5.8 release must bump its version to4.0.0 in its next release.Furthermore, when the library's4.0.0 release is out, its Definitely Typed type declaration package should also be updated to4.0.0, including any breaking changes to the library's API.
Many libraries have a large installed base of developers (including maintainers of other packages using that library as a dependency) who won't move right away to a new version that has breaking changes, because it might be months until a maintainer has time to rewrite code to adapt to the new version.In the meantime, users of old library versions still may want to update type declarations for older versions.
If you intend to continue updating the older version of a library's type declarations, you may create a new subfolder (e.g./v2/) named for the current (soon to be "old") version, and copy existing files from the current version to it.
Because the root folder should always contain the type declarations for the latest ("new") version, you'll need to make a few changes to the files in your old-version subdirectory to ensure that relative path references point to the subdirectory, not the root.
- Update the relative paths in
tsconfig.jsonas well astslint.json. - Add path mapping rules to ensure that tests are running against the intended version.
For example, thehistory library introduced breaking changes between version2.x and3.x.Because many users still consumed the older2.x version, a maintainer who wanted to update the type declarations for this library to3.x added av2 folder inside the history repository that contains type declarations for the older version.At the time of writing, thehistory v2tsconfig.json looks roughly like:
{"compilerOptions": {"baseUrl":"../../","typeRoots": ["../../"],"paths": {"history": ["history/v2" ] } },"files": ["index.d.ts","history-tests.ts" ]}If there are other packages in Definitely Typed that are incompatible with the new version, you will need to add path mappings to the old version.You will also need to do this recursively for packages depending on the old version.
For example,react-router depends onhistory@2, soreact-routertsconfig.json has a path mapping to"history": [ "history/v2" ].Transitively,react-router-bootstrap (which depends onreact-router) also needed to add the same path mapping ("history": [ "history/v2" ]) in itstsconfig.json until itsreact-router dependency was updated to the latest version.
Also,/// <reference types=".." /> will not work with path mapping, so dependencies must useimport.
The TypeScript handbook contains excellentgeneral information about writing definitions, and alsothis example definition file which shows how to create a definition using ES6-style module syntax, while also specifying objects made available to the global scope. This technique is demonstrated practically in thedefinition forbig.js, which is a library that can be loaded globally via script tag on a web page, or imported via require or ES6-style imports.
To test how your definition can be used both when referenced globally or as an imported module, create atest folder, and place two test files in there. Name oneYourLibraryName-global.test.ts and the otherYourLibraryName-module.test.ts. Theglobal test file should exercise the definition according to how it would be used in a script loaded on a web page where the library is available on the global scope - in this scenario you should not specify an import statement. Themodule test file should exercise the definition according to how it would be used when imported (including theimport statement(s)). If you specify afiles property in yourtsconfig.json file, be sure to include both test files. Apractical example of this is also available on thebig.js definition.
Please note that it is not required to fully exercise the definition in each test file - it is sufficient to test only the globally-accessible elements on the global test file and fully exercise the definition in the module test file, or vice versa.
Types for a scoped package@foo/bar should go intypes/foo__bar. Note the double underscore.
Whendts-gen is used to scaffold a scoped package, thepaths property has to be manually adapted in the generatedtsconfig.json to correctly reference the scoped package:
{"paths": {"@foo/*": ["foo__*"] }}GitHub doesn'tsupport file history for renamed files. Usegit log --follow instead.
This project is licensed under the MIT license.
Copyrights on the definition files are respective of each contributor listed at the beginning of each definition file.
About
The repository for high quality TypeScript type definitions.
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Languages
- TypeScript99.9%
- Other0.1%