Skip to content

Rule proposal: Prefer a named interface or type over inline object literals #8320

Closed as not planned
@JoshuaKGoldberg

Description

@JoshuaKGoldberg

Before You File a Proposal Please Confirm You Have Done The Following...

My proposal is suitable for this project

  • My proposal specifically checks TypeScript syntax, or it proposes a check that requires type information to be accurate.
  • My proposal is not a "formatting rule"; meaning it does not just enforce how code is formatted (whitespace, brace placement, etc).
  • I believe my proposal would be useful to the broader TypeScript community (meaning it is not a niche proposal).

Description

Sometimes folks write inline object type literals to represent objects in type annotations. For example, function parameters; return types; variable declarations. Two problems I see with these inline object literals:

  • They aren't named: so TypeScript errors and refactorings aren't as good
  • They clutter the syntax space around the function

Proposal: let's have a rule that bans object type literals in type annotations, with a configurable minimum number of object properties to report on? Let's say, banning types with >= 2 properties by default?

Fail Cases

let myValue: { apple: boolean; banana: boolean };

Pass Cases

interface Values {
  apple: boolean;
  banana: boolean;
}

let myValues: Values;

Additional Info

I'm not sure what the exact list of syntax locations should be. But "all type annotations" feels like a good start to me.

For auto-fixing, I can imagine this being useful in JSX-oriented libraries such as React if the auto-fixer creates a type with a name like {Component}Props when the type annotation is the first argument of a function that can be a JSX component.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions