Specify output directory for generated declaration files.
Requires TypeScript version 2.0 or later.
*/
declarationDir?:string;
/**
Show diagnostic information.
@default false
*/
diagnostics?:boolean;
/**
Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files.
@default false
*/
emitBOM?:boolean;
/**
Only emit `.d.ts` declaration files.
@default false
*/
emitDeclarationOnly?:boolean;
/**
Enable incremental compilation.
@default `composite`
*/
incremental?:boolean;
/**
Specify file to store incremental compilation information.
@default '.tsbuildinfo'
*/
tsBuildInfoFile?:string;
/**
Emit a single file with source maps instead of having a separate file.
@default false
*/
inlineSourceMap?:boolean;
/**
Emit the source alongside the sourcemaps within a single file.
Requires `--inlineSourceMap` to be set.
@default false
*/
inlineSources?:boolean;
/**
Specify JSX code generation: `'preserve'`, `'react'`, or `'react-native'`.
@default 'preserve'
*/
jsx?:CompilerOptions.JSX;
/**
Specifies the object invoked for `createElement` and `__spread` when targeting `'react'` JSX emit.
@default 'React'
*/
reactNamespace?:string;
/**
Print names of files part of the compilation.
@default false
*/
listFiles?:boolean;
/**
Specifies the location where debugger should locate map files instead of generated locations.
*/
mapRoot?:string;
/**
Specify module code generation: 'None', 'CommonJS', 'AMD', 'System', 'UMD', 'ES6', 'ES2015' or 'ESNext'. Only 'AMD' and 'System' can be used in conjunction with `--outFile`. 'ES6' and 'ES2015' values may be used when targeting 'ES5' or lower.
Report error when not all code paths in function return a value.
@default false
*/
noImplicitReturns?:boolean;
/**
Report errors for fallthrough cases in switch statement.
@default false
*/
noFallthroughCasesInSwitch?:boolean;
/**
Do not report errors on unreachable code.
@default false
*/
allowUnreachableCode?:boolean;
/**
Disallow inconsistently-cased references to the same file.
@default false
*/
forceConsistentCasingInFileNames?:boolean;
/**
Base directory to resolve non-relative module names.
*/
baseUrl?:string;
/**
Specify path mapping to be computed relative to baseUrl option.
*/
paths?:Record<string,string[]>;
/**
List of TypeScript language server plugins to load.
Requires TypeScript version 2.3 or later.
*/
plugins?:CompilerOptions.Plugin[];
/**
Specify list of root directories to be used when resolving modules.
*/
rootDirs?:string[];
/**
Specify list of directories for type definition files to be included.
Requires TypeScript version 2.0 or later.
*/
typeRoots?:string[];
/**
Type declaration files to be included in compilation.
Requires TypeScript version 2.0 or later.
*/
types?:string[];
/**
Enable tracing of the name resolution process.
@default false
*/
traceResolution?:boolean;
/**
Allow javascript files to be compiled.
@default false
*/
allowJs?:boolean;
/**
Do not truncate error messages.
@default false
*/
noErrorTruncation?:boolean;
/**
Allow default imports from modules with no default export. This does not affect code emit, just typechecking.
@default module === 'system' || esModuleInterop
*/
allowSyntheticDefaultImports?:boolean;
/**
Do not emit `'use strict'` directives in module output.
@default false
*/
noImplicitUseStrict?:boolean;
/**
Enable to list all emitted files.
Requires TypeScript version 2.0 or later.
@default false
*/
listEmittedFiles?:boolean;
/**
Disable size limit for JavaScript project.
Requires TypeScript version 2.0 or later.
@default false
*/
disableSizeLimit?:boolean;
/**
List of library files to be included in the compilation.
Requires TypeScript version 2.0 or later.
*/
lib?:CompilerOptions.Lib[];
/**
Enable strict null checks.
Requires TypeScript version 2.0 or later.
@default false
*/
strictNullChecks?:boolean;
/**
The maximum dependency depth to search under `node_modules` and load JavaScript files. Only applicable with `--allowJs`.
@default 0
*/
maxNodeModuleJsDepth?:number;
/**
Import emit helpers (e.g. `__extends`, `__rest`, etc..) from tslib.
Requires TypeScript version 2.1 or later.
@default false
*/
importHelpers?:boolean;
/**
Specify the JSX factory function to use when targeting React JSX emit, e.g. `React.createElement` or `h`.
Requires TypeScript version 2.1 or later.
@default 'React.createElement'
*/
jsxFactory?:string;
/**
Parse in strict mode and emit `'use strict'` for each source file.
Requires TypeScript version 2.1 or later.
@default false
*/
alwaysStrict?:boolean;
/**
Enable all strict type checking options.
Requires TypeScript version 2.3 or later.
@default false
*/
strict?:boolean;
/**
Enable stricter checking of of the `bind`, `call`, and `apply` methods on functions.
@default false
*/
strictBindCallApply?:boolean;
/**
Provide full support for iterables in `for-of`, spread, and destructuring when targeting `ES5` or `ES3`.
Requires TypeScript version 2.3 or later.
@default false
*/
downlevelIteration?:boolean;
/**
Report errors in `.js` files.
Requires TypeScript version 2.3 or later.
@default false
*/
checkJs?:boolean;
/**
Disable bivariant parameter checking for function types.
Requires TypeScript version 2.6 or later.
@default false
*/
strictFunctionTypes?:boolean;
/**
Ensure non-undefined class properties are initialized in the constructor.
Requires TypeScript version 2.7 or later.
@default false
*/
strictPropertyInitialization?:boolean;
/**
Emit `__importStar` and `__importDefault` helpers for runtime Babel ecosystem compatibility and enable `--allowSyntheticDefaultImports` for typesystem compatibility.
Requires TypeScript version 2.7 or later.
@default false
*/
esModuleInterop?:boolean;
/**
Allow accessing UMD globals from modules.
@default false
*/
allowUmdGlobalAccess?:boolean;
/**
Resolve `keyof` to string valued property names only (no numbers or symbols).
Requires TypeScript version 2.9 or later.
@default false
*/
keyofStringsOnly?:boolean;
/**
Emit ECMAScript standard class fields.
Requires TypeScript version 3.7 or later.
@default false
*/
useDefineForClassFields?:boolean;
/**
Generates a sourcemap for each corresponding `.d.ts` file.
Requires TypeScript version 2.9 or later.
@default false
*/
declarationMap?:boolean;
/**
Include modules imported with `.json` extension.
Requires TypeScript version 2.9 or later.
@default false
*/
resolveJsonModule?:boolean;
}
/**
Auto type (.d.ts) acquisition options for this project.
Requires TypeScript version 2.1 or later.
*/
exportinterfaceTypeAcquisition{
/**
Enable auto type acquisition.
*/
enable?:boolean;
/**
Specifies a list of type declarations to be included in auto type acquisition. For example, `['jquery', 'lodash']`.
*/
include?:string[];
/**
Specifies a list of type declarations to be excluded from auto type acquisition. For example, `['jquery', 'lodash']`.
*/
exclude?:string[];
}
exportinterfaceReferences{
/**
A normalized path on disk.
*/
path:string;
/**
The path as the user originally wrote it.
*/
originalPath?:string;
/**
True if the output of this reference should be prepended to the output of this project.
Only valid for `--outFile` compilations.
*/
prepend?:boolean;
/**
True if it is intended that this reference form a circularity.
*/
circular?:boolean;
}
}
exportinterfaceTsConfigJson{
/**
Instructs the TypeScript compiler how to compile `.ts` files.
*/
compilerOptions?:TsConfigJson.CompilerOptions;
/**
Auto type (.d.ts) acquisition options for this project.
Requires TypeScript version 2.1 or later.
*/
typeAcquisition?:TsConfigJson.TypeAcquisition;
/**
Enable Compile-on-Save for this project.
*/
compileOnSave?:boolean;
/**
Path to base configuration file to inherit from.
Requires TypeScript version 2.1 or later.
*/
extends?:string;
/**
If no `files` or `include` property is present in a `tsconfig.json`, the compiler defaults to including all files in the containing directory and subdirectories except those specified by `exclude`. When a `files` property is specified, only those files and those specified by `include` are included.
*/
files?:string[];
/**
Specifies a list of files to be excluded from compilation. The `exclude` property only affects the files included via the `include` property and not the `files` property.
Glob patterns require TypeScript version 2.0 or later.
*/
exclude?:string[];
/**
Specifies a list of glob patterns that match files to be included in compilation.
If no `files` or `include` property is present in a `tsconfig.json`, the compiler defaults to including all files in the containing directory and subdirectories except those specified by `exclude`.
Convert a union type to an intersection type using [distributive conditional types](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#distributive-conditional-types).
Inspired by [this Stack Overflow answer](https://stackoverflow.com/a/50375286/2172153).
@example
```
import {UnionToIntersection} from 'type-fest';
type Union = {the(): void} | {great(arg: string): void} | {escape: boolean};
Unlike a simpler split, this one includes the delimiter splitted on in the resulting array literal. This is to enable splitting on, for example, upper-case characters.
If you find this useful, please consider supporting my work with a [donation](https://humanwhocodes.com/donate).
## Description
A config array is a way of managing configurations that are based on glob pattern matching of filenames. Each config array contains the information needed to determine the correct configuration for any file based on the filename.
## Background
In 2019, I submitted an [ESLint RFC](https://github.com/eslint/rfcs/pull/9) proposing a new way of configuring ESLint. The goal was to streamline what had become an increasingly complicated configuration process. Over several iterations, this proposal was eventually born.
The basic idea is that all configuration, including overrides, can be represented by a single array where each item in the array is a config object. Config objects appearing later in the array override config objects appearing earlier in the array. You can calculate a config for a given file by traversing all config objects in the array to find the ones that match the filename. Matching is done by specifying glob patterns in `files` and `ignores` properties on each config object. Here's an example:
```js
exportdefault[
// match all JSON files
{
name:"JSON Handler",
files:["**/*.json"],
handler:jsonHandler
},
// match only package.json
{
name:"package.json Handler",
files:["package.json"],
handler:packageJsonHandler
}
];
```
In this example, there are two config objects: the first matches all JSON files in all directories and the second matches just `package.json` in the base path directory (all the globs are evaluated as relative to a base path that can be specified). When you retrieve a configuration for `foo.json`, only the first config object matches so `handler` is equal to `jsonHandler`; when you retrieve a configuration for `package.json`, `handler` is equal to `packageJsonHandler` (because both config objects match, the second one wins).
When you create a new instance of `ConfigArray`, you must pass in two arguments: an array of configs and an options object. The array of configs is most likely read in from a configuration file, so here's a typical example:
This example reads in an object or array from `my.config.js` and passes it into the `ConfigArray` constructor as the first argument. The second argument is an object specifying the `basePath` (the directoy in which `my.config.js` is found) and a `schema` to define the additional properties of a config object beyond `files`, `ignores`, and `name`.
### Specifying a Schema
The `schema` option is required for you to use additional properties in config objects. The schema is object that follows the format of an [`ObjectSchema`](https://npmjs.com/package/@humanwhocodes/object-schema). The schema specifies both validation and merge rules that the `ConfigArray` instance needs to combine configs when there are multiple matches. Here's an example:
Config arrays can be multidimensional, so it's possible for a config array to contain another config array, such as:
```js
exportdefault[
// JS config
{
files:["**/*.js"],
handler:jsHandler
},
// JSON configs
[
// match all JSON files
{
name:"JSON Handler",
files:["**/*.json"],
handler:jsonHandler
},
// match only package.json
{
name:"package.json Handler",
files:["package.json"],
handler:packageJsonHandler
}
],
// filename must match function
{
files:[filePath=>filePath.endsWith(".md")],
handler:markdownHandler
},
// filename must match all patterns in subarray
{
files:[["*.test.*","*.js"]],
handler:jsTestHandler
},
// filename must not match patterns beginning with !
{
name:"Non-JS files",
files:["!*.js"],
settings:{
js:false
}
}
];
```
In this example, the array contains both config objects and a config array. When a config array is normalized (see details below), it is flattened so only config objects remain. However, the order of evaluation remains the same.
If the `files` array contains a function, then that function is called with the absolute path of the file and is expected to return `true` if there is a match and `false` if not. (The `ignores` array can also contain functions.)
If the `files` array contains an item that is an array of strings and functions, then all patterns must match in order for the config to match. In the preceding examples, both `*.test.*` and `*.js` must match in order for the config object to be used.
If a pattern in the files array begins with `!` then it excludes that pattern. In the preceding example, any filename that doesn't end with `.js` will automatically getting a `settings.js` property set to `false`.
### Config Functions
Config arrays can also include config functions. A config function accepts a single parameter, `context` (defined by you), and must return either a config object or a config array (it cannot return another function). Config functions allow end users to execute code in the creation of appropriate config objects. Here's an example:
```js
exportdefault[
// JS config
{
files:["**/*.js"],
handler:jsHandler
},
// JSON configs
function(context){
return[
// match all JSON files
{
name:context.name+" JSON Handler",
files:["**/*.json"],
handler:jsonHandler
},
// match only package.json
{
name:context.name+" package.json Handler",
files:["package.json"],
handler:packageJsonHandler
}
];
}
];
```
When a config array is normalized, each function is executed and replaced in the config array with the return value.
**Note:** Config functions cannot be async. This will be added in a future version.
### Normalizing Config Arrays
Once a config array has been created and loaded with all of the raw config data, it must be normalized before it can be used. The normalization process goes through and flattens the config array as well as executing all config functions to get their final values.
To normalize a config array, call the `normalize()` method and pass in a context object:
```js
awaitconfigs.normalize({
name:"MyApp"
});
```
The `normalize()` method returns a promise, so be sure to use the `await` operator. The config array instance is normalized in-place, so you don't need to create a new variable.
**Important:** Once a `ConfigArray` is normalized, it cannot be changed further. You can, however, create a new `ConfigArray` and pass in the normalized instance to create an unnormalized copy.
### Getting Config for a File
To get the config for a file, use the `getConfig()` method on a normalized config array and pass in the filename to get a config for:
The config array always returns an object, even if there are no configs matching the given filename. You can then inspect the returned config object to determine how to proceed.
A few things to keep in mind:
* You must pass in the absolute filename to get a config for.
* The returned config object never has `files`, `ignores`, or `name` properties; the only properties on the object will be the other configuration options specified.
* The config array caches configs, so subsequent calls to `getConfig()` with the same filename will return in a fast lookup rather than another calculation.
## Acknowledgements
The design of this project was influenced by feedback on the ESLint RFC, and incorporates ideas from:
* Never return original object from individual config ([5463c5c](https://www.github.com/humanwhocodes/object-schema/commit/5463c5c6d2cb35a7b7948dffc37c899a41d1775f))