Rule: no-object-literal-type-assertion

Forbids an object literal to appear in a type assertion expression. Casting to any or to unknown is still allowed.

Rationale

Always prefer const x: T = { ... }; to const x = { ... } as T;. The type assertion in the latter case is either unnecessary or hides an error. The compiler will warn for excess properties with this syntax, but not missing required fields. For example: const x: { foo: number } = {} will fail to compile, but const x = {} as { foo: number } will succeed.

Notes:
TS Only

Config

One option may be configured:

  • allow-arguments allows type assertions to be used on object literals inside call expressions.
Config examples
"no-object-literal-type-assertion": true
"no-object-literal-type-assertion": [true, {"allow-arguments": true}]
Schema
{
  "type": "object",
  "properties": {
    "allow-arguments": {
      "type": "boolean"
    }
  },
  "additionalProperties": false
}

Code examples:

Disallow object literals to appear in type assertion expressions (default). Casing to `any` and `unknown` is allowed.
"rules": { "no-object-literal-type-assertion": true }
Passes
let foo = {} as any;
let foo = {} as unknown;

let foo = {} as any as Foo;
let foo = {} as unknown as Foo;
Fails
let foo = {} as Foo;
let foo = <Foo>{};
Allow using a type assertion when the object literal is used as an argument.
"rules": { "no-object-literal-type-assertion": [true, { "allow-arguments": true }] }
Passes
bar({} as Foo)