consistent-indexed-object-style
Require or disallow the
Record
type.
Extending "plugin:@typescript-eslint/stylistic"
in an ESLint configuration enables this rule.
Some problems reported by this rule are automatically fixable by the --fix
ESLint command line option.
Some problems reported by this rule are manually fixable by editor suggestions.
TypeScript supports defining arbitrary object keys using an index signature or mapped type.
TypeScript also has a builtin type named Record
to create an empty object defining only an index signature.
For example, the following types are equal:
interface IndexSignatureInterface {
[key: string]: unknown;
}
type IndexSignatureType = {
[key: string]: unknown;
};
type MappedType = {
[key in string]: unknown;
};
type RecordType = Record<string, unknown>;
Using one declaration form consistently improves code readability.
- Flat Config
- Legacy Config
export default tseslint.config({
rules: {
"@typescript-eslint/consistent-indexed-object-style": "error"
}
});
module.exports = {
"rules": {
"@typescript-eslint/consistent-indexed-object-style": "error"
}
};
Try this rule in the playground ↗
Options
This rule accepts the following options:
type Options = [
/** Which indexed object syntax to prefer. */
| 'index-signature'
/** Which indexed object syntax to prefer. */
| 'record',
];
const defaultOptions: Options = ['record'];
'record'
(default): only allow theRecord
type.'index-signature'
: only allow index signatures.
'record'
- ❌ Incorrect
- ✅ Correct
interface IndexSignatureInterface {
[key: string]: unknown;
}
type IndexSignatureType = {
[key: string]: unknown;
};
type MappedType = {
[key in string]: unknown;
};
Open in Playgroundtype RecordType = Record<string, unknown>;
Open in Playground'index-signature'
- ❌ Incorrect
- ✅ Correct
type RecordType = Record<string, unknown>;
Open in Playgroundinterface IndexSignatureInterface {
[key: string]: unknown;
}
type IndexSignatureType = {
[key: string]: unknown;
};
type MappedType = {
[key in string]: unknown;
};
Open in PlaygroundWhen Not To Use It
This rule is purely a stylistic rule for maintaining consistency in your project. You can turn it off if you don't want to keep a consistent style for indexed object types.
However, keep in mind that inconsistent style can harm readability in a project. We recommend picking a single option for this rule that works best for your project.