About
library definition file are known in typesecript/javascript as declaration files or .d.ts files. They describe the library in terms of class, function, type.
They are ambient.
By default, all visible @types packages are included in your compilation.
Packages in node_modules/@types of any enclosing folder are considered visible; that means packages within
- ./node_modules/@types/,
- ../node_modules/@types/,
- ../../node_modules/@types/,
- and so on are visible.
How does typescript or your IDE find declaration files locally
See How does typescript or your IDE find type declaration files (d.ts)?
Typings Package
Typings package are package with the typing type and ship only declaration files.
Search: the package names follow this pattern: @types/library-name
Installation
Example with lodash
yarn add @types/lodash --dev
// or
npm install -S @types/lodash
Repository containing these files for each library.
- See DefinitelyTyped
Syntax
Global Variable
/** The number of widgets present */
declare var foo: number;
declare const foo: number; // Read only
declare let foo: number; // Block scoped
Function
- declare function declare functions
declare function greet(greeting: string): void;
Objects with Properties (Namespace)
- declare namespace to declare to describe types or values accessed by dotted notation
declare namespace myLib {
function makeGreeting(s: string): string;
let numberOfGreetings: number;
}
Overloaded function
Function - Overloaded Function (Overloaded)
declare function getWidget(n: number): Widget;
declare function getWidget(s: string): Widget[];
Compiler
Creation with tsc command line
with Typescript - tsc (official compiler)
tsc --declaration ./js/index.ts
# or
tsc --declaration -p tsconfig.json
where:
- -d or –declaration generates a '.d.ts' file.
Creation with tsconfig and jsx
{
// Your project
"include": ["src/**/*"],
"compilerOptions": {
// Tells TypeScript to read JS files, as
// normally they are ignored as source files
"allowJs": true,
// Generate d.ts files
"declaration": true,
// This compiler run should only output d.ts files
// to not overwrite the js file
"emitDeclarationOnly": true,
// Types should go into this directory.
// Removing this would place the .d.ts files
// next to the .js files
"outDir": "dist",
// go to js file when using IDE functions like
// "Go to Definition" in VSCode
"declarationMap": true,
// exclude errors in types from dependencies libraries
"skipLibCheck": true,
// Allows jsx
"allowImportingTsExtensions": true,
"jsx": "react-jsx",
// ??? React can only be used with a default import when using the 'esModuleInterop' flag
"esModuleInterop": true
}
}
- then with tsc
tsc --project tsconfig.types.json
- then in your package.json
{
"types":"/dist/index.d.ts"
}