typescript-eslint: [no-object-literal-type-assertion] False positive when asserting function argument

Repro

module.exports = {
    root: true,
    plugins: ["typescript"],
    parser: "typescript-eslint-parser",
    extends: ["plugin:typescript/recommended"],
}
interface Foo {
    foo?: number;
}

function print(x: Foo): void {
    console.log(x.foo)
}

print({ bar: 5 } as Foo)

Expected Result

No errors.

Actual Result

/Users/semenov/tmp/ts-rule/test.ts
  9:7  error  Type assertion on object literals is forbidden, use a type annotation instead  typescript/no-object-literal-type-assertion

✖ 1 problem (1 error, 0 warnings)

Additional Info

The primary purpose of the rule (as I see it) is to prevent object assignment such as const x = { ... } as T; which is better rewritten as const x: T = { ...};, but the rule disallows all other legitimate uses.

Versions

package version
eslint-plugin-typescript 1.0.0-rc.2
typescript-eslint-parser 21.0.2
typescript 3.2.2

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Comments: 15 (4 by maintainers)

Most upvoted comments

@armano2 I am well aware of augmenting external modules, thank you. In this particular case the typings already make sense:

type PartialUpdate<QM extends Model> = {
  [P in keyof QM]?: QM[P] | Raw | Reference | QueryBuilder<any, any[]>
};

interface QueryBuilderBase<QM extends Model, RM, RV> extends QueryInterface<QM, RM, RV> {
  patch(modelOrObject: PartialUpdate<QM>): QueryBuilderYieldingCount<QM, RM>;
}

Extending the interface for modelOrObject to T extends PartialUpdate will break the guards for ‘normal’ field updates (not using JSON subfields).

In either case, let’s not do Typescript learning sessions here, this issue is about something completely different and is irrelevant to my comprehension of TS and/or possibility of other workarounds.

type assertion and type casing is awesome during migration of code, but when you finish you want to avoid using it, otherwise there is no point in using typescript if you just cas everything to incompatible types.

adding option is great idea (more ways to configure = better), but by default it should just warn about all of usages…

I’m of the opinion that you can never have enough options!

I suspect that it should by default only flag VariableDeclarators (need to check TSLint’s behaviour to confirm) But I wouldn’t be opposed to adding this case as an option

Honestly I don’t see why linter should be bothering with what’s Typescript doing just fine by itself?

Over the years we’ve generally found that there will be some amount of overlap between the linter & compiler checks; it’s not a black & white distinction (https://github.com/palantir/tslint/issues/4100 is just one example). I agree with @bradzacher’s stated goal for this plugin: “This plugin exists to complement the compiler, to enforce some conventions on code that is probably 100% valid.” The TS type system is very flexible & gradual and this is good for incremental adoption, but for users who want to coerce the system to be more static & strict, we have lint rules.

What would you do if it’s a more complex scenario such as below?

IMO Partials are a TS code smell, they throw away some type safety and should be used sparingly (and therefore the lint rule shouldn’t be designed to suit them as a standard code pattern, but rather an edge case). That is an opinionated stance. Either way, the code in that example doesn’t compile, you get this error with TS 3.1.2:

[ts]
Argument of type 'Partial<Foo>' is not assignable to parameter of type 'Foo'.
  Types of property 'foo' are incompatible.
    Type 'number | undefined' is not assignable to type 'number'.
      Type 'undefined' is not assignable to type 'number'. [2345]

In cases where the compiler produces an error, I think it’s ok for the linter to also produce an error (at least, I don’t think it matters much in practice).

no-object-literal-type-assertion in TSLint is on the stricter side of core rules, and maybe you don’t want to enable it in your recommended ruleset (that’s fine), but I’ve generally found it pretty helpful in catching type errors as it exists right now.

I’d have to test tslint in this case, as this rule is intended to be a like-for-like reimplementation of that logic. Though I suspect that this is an implementation bug.


Honestly I don’t see why linter should be bothering with what’s Typescript doing just fine by itself?

This plugin exists to complement the compiler, to enforce some conventions on code that is probably 100% valid.

One could argue that your original code has a code smell, because it is passing more than the function signature is asking for - breaking its contract. I.e. consider this example:

interface Foo {
    foo?: number;
}

function apiReq(x: Foo): void {
	Object.keys(x).forEach(key => sendKVPToAPI(key, x[key]))
}

apiReq({ bar: 5 } as Foo)

This code is syntactically valid in TS, but doesn’t mean it’s semantically correct. When this runs, you’ll send invalid data to the API, because you’ve forced some behaviour via using the as keyword.

Whilst of course this is an exaggerated case, these things do happen, so you can see why people might want a lint rule to catch and help to prevent people using compile time correct code.

The above case is why flow has its “exact object” syntax, to enforce a stricter (unbreakable) type contract.

type Foo = {| // the |'s make it an exact type
    foo?: number;
|}

function apiReq(x: Foo): void {
	Object.keys(x).forEach(key => sendKVPToAPI(key, x[key]))
}

apiReq(
    ({ bar: 5 }: Foo), // yes, this is flow's type cast syntax
    //  ^ Cannot cast object literal to `Foo` because property `bar` is missing in `Foo`, but exists in object literal.
)