Sharp: Generate TypeScript typings, preferably automagically

Created on 22 Jun 2016  路  25Comments  路  Source: lovell/sharp

first of all thx for your amazing library. I am writing an application using sharp. I would like to use TypeScript but unfortunately your library doesn't come with typings included.

I already started implementing some of them and would like to know if its worth the work to complete them so you can include them into your package. You could also think about generating the docs from the type definitions.

declare module "sharp" {
  function s(input: string | Buffer, options?: any): s.ISharpImage;

  namespace s {
    interface ISharpImage {
      /**
       * Fast access to image metadata without decoding any compressed image data.
       */
      metadata(cb?: (error?: Error, metadata?: IMetadata) => void): void;
      /**
       * Takes a "snapshot" of the instance, returning a new instance. Cloned instances inherit the input of their parent instance.
       * 
       * This allows multiple output Streams and therefore multiple processing pipelines to share a single input Stream.
       */
      clone(): ISharpImage;
      resize(width?: number, height?: number, options?: any): ISharpImage;
      max(width?: number, height?: number): ISharpImage;
      min(width?: number, height?: number): ISharpImage;
      rotate(angle?: number): ISharpImage;
      toFile(path: string, callback?: (err?: Error, info?: any) => void): any;
    }

    /**
     * image metadata
     */
    interface IMetadata {
      /**
       * Name of decoder used to decompress image data e.g. `jpeg`, `png`, `webp`, `gif`, `svg`
       */
      format: 'jpeg' | 'png' | 'webp' | 'gif' | 'svg';
      /**
       * Number of pixels wide
       */
      width: number;
      /**
       * Number of pixels high
       */
      height: number;
      /**
       * Name of colour space interpretation e.g. srgb, rgb, scrgb, cmyk, lab, xyz, b-w ...
       */
      space: string;
      /**
       * Number of bands e.g. `3` for sRGB, `4` for CMYK
       */
      channels: number;
      /**
       * Boolean indicating the presence of an embedded ICC profile
       */
      hasProfile: boolean;
      /**
       * Boolean indicating the presence of an alpha transparency channel
       */
      hasAlpha: boolean;
      /**
       * Number value of the EXIF Orientation header, if present
       */
      orientation: number;
      /**
       * Buffer containing raw EXIF data, if present
       */
      exif: Buffer;
      /**
       * Buffer containing raw ICC profile data, if present
       */
      icc: Buffer;
    }
  }

  export = s;
}
enhancement

Most helpful comment

sure thing, I just stumbled upon issue 2916 in the typescript repository and there seem to be at least two possibilities. We could use closure-ts or maybe even the typescript compiler itself with the --alowJs flag.

I will dig a little more into this and give you some more info and feedback

All 25 comments

Hello, I'd be happy to provide support for more explicit typing.

Is there a way to automagically generate TypeScript typings inline via something like jsdocs? This would allow us to keep type definitions and documentation alongside the functions they describe, rather than in a separate file. (Generating the API docs from annotated source is something I'd also like to do.)

sure thing, I just stumbled upon issue 2916 in the typescript repository and there seem to be at least two possibilities. We could use closure-ts or maybe even the typescript compiler itself with the --alowJs flag.

I will dig a little more into this and give you some more info and feedback

Although flagged as experimental, https://github.com/englercj/tsd-jsdoc might be worth investigating.

I've added this to https://hacktoberfest.digitalocean.com/ as I feel it would make a great (first?) PR for someone who knows about TypeScript tooling. No need to delve into the C++ code for this one either.

Picking this up.

@lovell I have added a sharp.d.ts (Typescript definition file) as part of #596.

I have included instructions in a comment at the top of the sharp.d.ts file so that you can produce an up to date definition file with each release.

Thanks @BrianDGLS!

Please can someone interested in this feature help test/assess the usefulness of these auto-generated (mostly "any") bindings.

https://github.com/Microsoft/dts-gen/issues/2 looks like it could provide more specific type definitions based on JSDocs.

@lovell @BrianDGLS I think it is pretty fine to add the file with these "any" bindings for now. Like this it is already way more convenient instead of generating that file by your own (and your team). More specific type definitions are WIP and could be enhanced in parallel.

Running the following when on the quill branch:

npm install tsd-jsdoc jsdoc
./node_modules/.bin/jsdoc -d . -t node_modules/tsd-jsdoc lib/*.js

...automagically produces types.d.ts from the JSDoc comments.

Thank you Lovell. It would be a good improvement, if the npm repository already comes with that auto generated file.

Commit 6b42601 adds an experimental TypeScript declaration and the tooling to update it.

Is anyone able to test this?

The reference in the package.json works.
Nevertheless the file is not fully valid.

  • A description is thrown right into the declaration of declare var sharp: any.
  • The type of Sharp is not defined, e.g. declare function clone(): Sharp;.
declare var sharp

Constructor factory to create an instance of `sharp`, to which further methods are chained.

JPEG, PNG or WebP format image data can be streamed out from this object.
When using Stream based output, derived attributes are available from the `info` event.

Implements the [stream.Duplex](http://nodejs.org/api/stream.html#stream_class_stream_duplex) class.: any;

@janwo Thanks for testing. Does the following change to lib/constructor.js help?

- * @name sharp
+ * @class Sharp

You'll need to update types.d.ts after making this change:

npm run types

@lovell That did work! There are still minor issues:

  • Promises need a type (.e.g. Promise<any>)
  • There is an array without a type: Array -> Array<any>

@janwo Commit effa77a modifies the JSDoc comments to correct the problems you found, thank you!

I think these TypeScript definitions might be ready to :shipit: 馃帀

@lovell Almost! I pulled the repo, tried it again and there are still three errors due to a malformed conversion, e.g. Promise.<Object> instead of Promise<Object>. Object should work though.

node_modules/sharp/lib/types.d.ts(205,61): error TS1003: Identifier expected.
node_modules/sharp/lib/types.d.ts(795,75): error TS1003: Identifier expected.
node_modules/sharp/lib/types.d.ts(809,60): error TS1003: Identifier expected.

And when importing sharp, the following error occurs: Error:(16, 24) TS2306:File '..../sharp/lib/types.d.ts' is not a module.. Wrapping the whole types.d.ts with a module declaration, should solve that IMO.

Commit e4e7384 fixes the Promise<T> notation (via a patch to tsd-jsdoc) and adds the declare module "sharp" { ... } wrapper.

@janwo Are you able to re-test?

Yes, I did. There is still a lot todo I guess. All functions have to be within the class declaration. Types of String, Number, etc. have to be lowercase, e.g. somefunction(val: number). Then the declare parts should be removed. And I just realized that all functions of Sharp are not within the Sharp class, this needs to be done as well. Static functions have to be marked as static and so on.

Example:
```ts
declare module "sharp" {
export class Sharp {
somevar: number;
static somestaticvar: string;

    somefunction0(val:any) : void {};
    somefunction1(str: string) : Sharp {};
    somefunction2(str: string) : Sharp {};
}

}
````

Maybe someone else has an easier approach.

@janwo Is there a (semi-)automated tool you'd recommend for verifying TypeScript definition files?

I've removed the experimental automated definitions via commit dfd6d95. We can revisit this next year - thanks everyone for all your help so far!

I salute the effort to auto-create typings; in the meantime, though, here are typings I made by hand, if you'd like to use them.

Note that I only typed input, resize, operation, and output. The composite, colour, and channel APIs I can add if there is interest in pursuing this approach.

@mceachen Thank you. Perhaps you could submit your hand-rolled typings to https://github.com/DefinitelyTyped/DefinitelyTyped for others to help maintain?

@mceachen That would be helpful!

It looks like (hand-crafted) TypeScript definition files for sharp have landed in https://github.com/DefinitelyTyped/DefinitelyTyped/pull/14308

@dcharbonnier Regarding your 馃憥 I'd be happy to reconsider when the tooling for automated jsdoc to typescript bindings has improved. As always, PRs welcome to make things better.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Andresmag picture Andresmag  路  3Comments

terbooter picture terbooter  路  3Comments

OleVik picture OleVik  路  3Comments

iq-dot picture iq-dot  路  3Comments

genifycom picture genifycom  路  3Comments