Trying to utilize the notify function from an external library has been a bit challenging.
The declaration in the library is as follows:
// library.js
export declare const notify: {
(args: NotificationsOptions | string): void;
close(id: unknown): void;
};
Now the goal is to call the function with arguments that extend the original ones, like so:
// myFile.js
import { notify } from 'library';
const originalArgs = { /* object of type NotificationsOptions */ };
notify(originalArgs); // this works
notify({ ...originalArgs, additionalProperty: 'Foo' }); // results in TypeScript error message "Argument type {..., additionalProperty: string } is not assignable to parameter type NotificationsOptions | string"
While the issue is clear, finding the best practice to solve it remains a challenge.
A few potential solutions have been considered:
// myFile.js
// 1. Typecasting using "as" notation:
import { notify } from 'library';
notify({ ...originalArgs, additionalProperty: 'Foo' } as NotificationOptions); // works, but feels unclean since it's not truly of this type?
// 2. Disabling inspection with ts-ignore
// It works, but is it really the cleanest solution?
// 3. Disabling inspection by passing in as a predefined constant:
import { notify } from 'library';
const extendedArgs = { ...originalArgs, additionalProperty: 'Foo' };
notify(extendedArgs); // works, but not ideal since the check is only implicitly disabled
// 4. Redeclaring notify:
import { notify } from 'library';
declare const notify: {
(args: NotificationOptions & { additionalProperty: string}): void;
}; // Results in an error "Import declaration conflicts with local declaration of 'notify'
notify({ ...originalArgs, additionalProperty: 'Foo' });
// 5. Avoid using import
declare const notify: {
(args: NotificationOptions & { additionalProperty: string}): void;
};
notify({ ...originalArgs, additionalProperty: 'Foo' }); // No TypeScript error, but runtime error "notify is not defined"
// 6. Declare extendedNotify
// This might be the preferred solution, but figuring out how to implement it is a challenge
import { notify } from 'library';
declare const extendedNotify: {
(args: NotificationOptions & { additionalProperty: string }): void;
};
notify({ ...originalArgs, additionalProperty: 'Foo' }) as extendedNotify; // Resolved type extendedNotify