Consider the TypeScript code snippet below:
type Primitive = undefined | null | boolean | number | string;
// A POJO is simply meant to represent a basic object, without any complexities, where the content is unknown.
interface POJO {
[key: string]: Primitive | POJO;
}
The POJO here serves as a generic object, intended for simple usage like converting it to JSON or similar processes. However, an issue arises in the following code block:
// Implementation of certain functions elsewhere...
declare function post(path: string, data: POJO): Promise<Response>;
declare function getToken(): string;
type LinkOrMessage = {link: string} | {message: string};
function specialPost(path: string, data: LinkOrMessage): Promise<Response> {
const body = {
...data,
token: getToken(),
};
// Error explanation provided below...
return post(path, body);
}
The error message states:
Argument of type '{ token: string; link: string; } | { token: string; message: string; }'
is not assignable to parameter of type 'POJO'.
Type '{ token: string; link: string; }'
is not assignable to type 'POJO'.
Index signature is missing in type '{ token: string; link: string; }'
This prompts confusion. Interestingly, simplifying the LinkOrMessage
type by selecting only {link: string}
or {message: string}
resolves the error. Each individual type in the union seems compatible with POJO
, yet the union itself poses an issue?
If anyone could provide insight into this behavior, it would be greatly appreciated.