consistent-type-definitions
Enforce type definitions to consistently use either
interface
ortype
.
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.
TypeScript provides two common ways to define an object type: interface
and type
.
// type alias
type T1 = {
a: string;
b: number;
};
// interface keyword
interface T2 {
a: string;
b: number;
}
The two are generally very similar, and can often be used interchangeably. Using the same type declaration style consistently helps with code readability.
- Flat Config
- Legacy Config
export default tseslint.config({
rules: {
"@typescript-eslint/consistent-type-definitions": "error"
}
});
module.exports = {
"rules": {
"@typescript-eslint/consistent-type-definitions": "error"
}
};
Try this rule in the playground ↗
Options
This rule accepts the following options:
type Options = [
/** Which type definition syntax to prefer. */
| 'type'
/** Which type definition syntax to prefer. */
| 'interface',
];
const defaultOptions: Options = ['interface'];
'interface'
(default): enforce usinginterface
s for object type definitions.'type'
: enforce usingtype
s for object type definitions.
'interface'
- ❌ Incorrect
- ✅ Correct
type T = { x: number };
Open in Playgroundtype T = string;
type Foo = string | {};
interface T {
x: number;
}
Open in Playground'type'
- ❌ Incorrect
- ✅ Correct
interface T {
x: number;
}
Open in Playgroundtype T = { x: number };
Open in PlaygroundWhen Not To Use It
If you specifically want to use an interface or type literal for stylistic reasons, you can avoid this rule.
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.
There are also subtle differences between Record
and interface
that can be difficult to catch statically.
For example, if your project is a dependency of another project that relies on a specific type definition style, this rule may be counterproductive.
You might consider using ESLint disable comments for those specific situations instead of completely disabling this rule.