Skip to content

Commit

Permalink
Allow unknown in 'no-object-literal-type-assertion' rule. (palantir#4362
Browse files Browse the repository at this point in the history
)

* Fix palantir#4355 Allow unknown in 'no-object-literal-type-assertion' rule.

* Allow unknown in TS 2.0 as well.

* Allow unknown type assertion
  • Loading branch information
NN--- authored and Josh Goldberg committed Dec 12, 2018
1 parent 5d9f1bd commit e8a620d
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/rules/noObjectLiteralTypeAssertionRule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export class Rule extends Lint.Rules.AbstractRule {
ruleName: "no-object-literal-type-assertion",
description: Lint.Utils.dedent`
Forbids an object literal to appear in a type assertion expression.
Casting to \`any\` is still allowed.`,
Casting to \`any\` or to \`unknown\` 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 Down Expand Up @@ -58,6 +58,10 @@ function walk(ctx: Lint.WalkContext<void>): void {
if (
isAssertionExpression(node) &&
node.type.kind !== ts.SyntaxKind.AnyKeyword &&
// Compare with UnknownKeyword if using TS 3.0 or above
(!!(ts.SyntaxKind as any).UnknownKeyword ?
(node.type.kind !== (ts.SyntaxKind as any).UnknownKeyword) :
node.type.getText(ctx.sourceFile) !== "unknown") &&
isObjectLiteralExpression(
isParenthesizedExpression(node.expression)
? node.expression.expression
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 @@ -12,4 +12,8 @@ x as T;
{} as any;
<any> {};

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

[0]: Type assertion on object literals is forbidden, use a type annotation instead.

0 comments on commit e8a620d

Please sign in to comment.