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]
The error "Argument of type is not assignable to parameter of type 'never'" occurs when we declare an empty array without explicitly typing it and attempt to add elements to it. To solve the error, explicitly type the empty array, e.g. const arr: string[] = []; .
The error "Argument of type string | undefined is not assignable to parameter of type string" occurs when a possibly undefined value is passed to a function that expects a string . To solve the error, use a type guard to verify the value is a string before passing it to the function.
The "Type 'string' is not assignable to type" TypeScript error occurs when we try to assign a value of type string to something that expects a different type, e.g. a more specific string literal type or an enum. To solve the error use a const or a type assertion.
The "Type 'void' is not assignable to type" TypeScript error occurs when we forget to return a value from a function, so the function gets an implicit return type of void . To solve the error, make sure you return a value of the correct type from your functions before the assignment.
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.
Perhaps you meant to use any
(instead of object
). any
is compatible with everything.
Use the exact type i.e. MyInterface
interface MyInterface {
type: string;
}
let arr:MyInterface[] = []; // Add correct annotation 🌹
arr.sort((a: MyInterface, b: MyInterface) => {});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With