Skip to content
This repository has been archived by the owner on Mar 25, 2021. It is now read-only.

no-object-literal-type-assertion: Enable and allow cast to 'any' #2671

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/rules/completedDocsRule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,7 @@ abstract class Requirement<TDescriptor extends RequirementDescriptor> {
}
}

// tslint:disable-next-line no-object-literal-type-assertion
protected constructor(public readonly descriptor: TDescriptor = {} as TDescriptor) { }

public abstract shouldNodeBeDocumented(node: ts.Declaration): boolean;
Expand Down
6 changes: 4 additions & 2 deletions src/rules/noObjectLiteralTypeAssertionRule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@ export class Rule extends Lint.Rules.AbstractRule {
/* tslint:disable:object-literal-sort-keys */
public static metadata: Lint.IRuleMetadata = {
ruleName: "no-object-literal-type-assertion",
description: "Forbids an object literal to appear in a type assertion expression.",
description: Lint.Utils.dedent`
Forbids an object literal to appear in a type assertion expression.
Casting to \`any\` is still allowed.`,
rationale: Lint.Utils.dedent`
Always prefer \`const x: T = { ... };\` to \`const x = { ... } as T;\`.
The type assertion in the latter case is either unnecessary or hides an error.
Expand All @@ -45,7 +47,7 @@ export class Rule extends Lint.Rules.AbstractRule {

function walk(ctx: Lint.WalkContext<void>): void {
return ts.forEachChild(ctx.sourceFile, function cb(node: ts.Node): void {
if (isTypeAssertionLike(node) && isObjectLiteral(node.expression)) {
if (isTypeAssertionLike(node) && isObjectLiteral(node.expression) && node.type.kind !== ts.SyntaxKind.AnyKeyword) {
ctx.addFailureAtNode(node, Rule.FAILURE_STRING);
}
return ts.forEachChild(node, cb);
Expand Down
4 changes: 4 additions & 0 deletions test/rules/no-object-literal-type-assertion/test.ts.lint
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,8 @@

x as T;

// Allow cast to 'any'
{} as any;
<any> {};

[0]: Type assertion applied to object literal.
3 changes: 1 addition & 2 deletions tslint.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@
"no-magic-numbers": false,
"no-non-null-assertion": false,
"no-null-keyword": false,
"no-object-literal-type-assertion": false,
"no-require-imports": false,
"no-unbound-method": false,
"no-unnecessary-callback-wrapper": false,
Expand Down Expand Up @@ -82,7 +81,7 @@
"public-before-private",
"static-before-instance",
"variables-before-functions"
],
],
"no-console": {
"options": ["log"]
},
Expand Down