Issue
I'm using the package @types/cropperjs
unfortunately it is behind the current cropper.js versions and lacks the method scale
.
So far I just manually added the missing method to the d.ts file under node_modules (this is obviously a bad idea, so don't do that! it was just a temp. fix)
I tried to merge the definitions from node_modules
with my own declaration.
declare class cropperjs {
/**
* Scale the image.
*
* @param scaleX The scaling factor to apply on the abscissa of the image.
* When equal to 1 it does nothing. Default is 1
* @param scaleY The scaling factor to apply on the ordinate of the image.
* If not present, its default value is scaleX.
*/
scale(scaleX: number, scaleY?: number): void;
}
export = cropperjs;
export as namespace Cropper;
the typings from the DefinitlyTyped Repo can be found on github (it looks similar but is too big to display here)
Here's how I import cropper in an angular component.
import * as Cropper from 'cropperjs';
Here's my tsconfig.json (parts of it)
"typeRoots": [
"node_modules/@types",
"node_modules/@angular",
"src/typings"
],
"types": [
"jasmine",
"node",
"karma",
"webpack",
"cropperjs"
]
I tried it with my custom typings folder an with the tripple slash reference notation. But I can't figure out how I can successfully merge my and DefinitlyTyped's definitions so I can use cropperjs without having to fiddle around in node_module
P.S. I already opened an issue with the updated definitions on github (no pull request, because at the time had almost no knowledge of git).
Solution
As far as I know, you can't do that in typescript. Typescript has the concept of declaration merging, which is what allows us to extend types other people wrote, and you can merge interface and namespaces, but not classes. Look here.
If the @types/cropperjs
would have been written using interfaces, you could have extended that interface using your own declaration.
Here is an ugly hack you can do for now:
import * as Cropper from 'cropperjs';
interface MyCropper extends Cropper {
scale(scaleX: number, scaleY?: number): void;
}
function CreateCropper(dom: HTMLImageElement, options: Cropper.CropperOptions): MyCropper {
return new Cropper(dom, options) as MyCropper;
}
casting is always ugly, but at least you hide it in one place, I think it's reasonable...
Answered By - Aviad Hadad
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.