skube
skube

Reputation: 6175

Argument of type '...' is not assignable to parameter of type '...' TS 2345

Given the following:

interface MyInterface {
  type: string;
}

let arr: object[] = [ {type: 'asdf'}, {type: 'qwerty'}]

// Alphabetical sort
arr.sort((a: MyInterface, b: MyInterface) => {
      if (a.type < b.type) return -1;
      if (a.type > b.type) return 1;
      return 0;
    });

Can someone help decipher the TS error:

// TypeScript Error
[ts]
Argument of type '(a: MyInterface, b: MyInterface) => 0 | 1 | -1' is not assignable to parameter of type '(a: object, b: object) => number'.
  Types of parameters 'a' and 'a' are incompatible.
    Type '{}' is missing the following properties from type 'MyInterface': type [2345]

Upvotes: 23

Views: 129626

Answers (2)

1.21 gigawatts
1.21 gigawatts

Reputation: 17870

If an object is already of a defined type it may cause this error.

// does not work
var user = aws.results.Item;
user = getUserType(user);
doSomething(user);

// works
var user = aws.results.Item;
var userTyped = getUserType(user);
doSomething(userTyped);

// typed user parameter
function doSomething(user: User) {}

Instead of reusing an existing reference create a new one.

Upvotes: 1

basarat
basarat

Reputation: 276323

Here is a simplified example to reproduce the error:

interface MyInterface {
  type: string;
}
let arr:object[] = []
// Error: "object" is not compatible with MyInterface 
arr.sort((a: MyInterface, b: MyInterface) => {});

The reason its an error is because object cannot be assigned to something that is of type MyInterface:

interface MyInterface {
  type: string;
}
declare let foo: object;
declare let bar: MyInterface;
// ERROR: object not assignable to MyInterface
bar = foo; 

And the reason this is an error is because object is synonymous with {}. {} does not have the type property and therefore incompatible with MyInterface.

Fix

Perhaps you meant to use any (instead of object). any is compatible with everything.

Better fix

Use the exact type i.e. MyInterface

interface MyInterface {
  type: string;
}
let arr:MyInterface[] = []; // Add correct annotation 🌹
arr.sort((a: MyInterface, b: MyInterface) => {});

Upvotes: 23

Related Questions