As outlined in the documentation for interfaces in TypeScript,
An interface declaration serves as an alternative way to define an object type.
I'm puzzled by the error I encounter in the following code snippet. My attempt is to restrict the object
type within the arrow function parameter using an interface.
(Try it out on TypeScript Playground)
interface Person {
name: string;
}
type ObjToString = (obj: object) => string;
const personToString: ObjToString = (obj: Person) => obj.name;
// This leads to the error ^^^^^^
The error message states:
Type '(obj: Person) => string' is not compatible with type 'ObjToString'.
The parameters 'obj' are of conflicting types.
Property 'name' is required in type 'Person' but missing in type '{}'.
Interestingly, assigning a variable of type Person
to a variable of type object
poses no issue:
let obj: object;
const person: Person = { name: "Tom" };
obj = person; // No problem here
Why does the error appear specifically at the arrow function parameter? What steps can be taken to resolve this issue?