Thanks to visit codestin.com
Credit goes to github.com

Skip to content

feat(eslint-plugin): add option to no-object-literal-type-assertion rule #87

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Jan 22, 2019
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,11 @@ const z = { ... } as unknown;

## Options

```json
```cjson
{
"@typescript-eslint/no-object-literal-type-assertion": "error"
"@typescript-eslint/no-object-literal-type-assertion": ["error", {
allowAsParameter: false // Allow type assertion in call and new expression, default false
}]
}
```

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@ const util = require('../util');
// Rule Definition
//------------------------------------------------------------------------------

const defaultOptions = [
{
allowAsParameter: false
}
];

module.exports = {
meta: {
type: 'problem',
Expand All @@ -25,9 +31,24 @@ module.exports = {
unexpectedTypeAssertion:
'Type assertion on object literals is forbidden, use a type annotation instead.'
},
schema: []
schema: [
{
type: 'object',
additionalProperties: false,
properties: {
allowAsParameter: {
type: 'boolean'
}
}
}
]
},
create(context) {
const { allowAsParameter } = util.applyDefault(
defaultOptions,
context.options
)[0];

//----------------------------------------------------------------------
// Public
//----------------------------------------------------------------------
Expand All @@ -52,6 +73,14 @@ module.exports = {

return {
'TSTypeAssertion, TSAsExpression'(node) {
if (
allowAsParameter &&
(node.parent.type === 'NewExpression' ||
node.parent.type === 'CallExpression')
) {
return;
}

if (
checkType(node.typeAnnotation) &&
node.expression.type === 'ObjectExpression'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,23 @@ ruleTester.run('no-object-literal-type-assertion', rule, {
`const foo = <any> {};`,
// Allow cast to 'unknown'
`const foo = {} as unknown;`,
`const foo = <unknown> {};`
`const foo = <unknown> {};`,
{
code: `print({ bar: 5 } as Foo)`,
options: [
{
allowAsParameter: true
}
]
},
{
code: `new print({ bar: 5 } as Foo)`,
options: [
{
allowAsParameter: true
}
]
}
],
invalid: [
{
Expand Down Expand Up @@ -71,6 +87,26 @@ ruleTester.run('no-object-literal-type-assertion', rule, {
column: 11
}
]
},
{
code: `print({ bar: 5 } as Foo)`,
errors: [
{
messageId: 'unexpectedTypeAssertion',
line: 1,
column: 7
}
]
},
{
code: `new print({ bar: 5 } as Foo)`,
errors: [
{
messageId: 'unexpectedTypeAssertion',
line: 1,
column: 11
}
]
}
]
});