flow icon indicating copy to clipboard operation
flow copied to clipboard

Document `constructor` functions in classes.

Open btipling opened this issue 11 years ago • 7 comments

I noticed that in the flow lib code that use of a special constructor function declaration is used but it's not documented on the website. I've tried to use it but it has so far led to errors, so I have to go through the flow source code some more to figure it out, but here is an example of it in lib/node.js:

declare class Buffer {
  constructor(value: Array<number> | number | string, encoding?: string): void;
 ...
}

constructor should probably be included in the Classes documentation.

What I've tried to do is in an interface is:

declare class DiffMatchPatch {
  constructor(): void;
}

declare var diff_match_patch: DiffMatchPatch;

and then try to use new diff_match_patch(); in our @flow weak code but it blows up saying Constructor cannot be called even though I defined it in the interface file.

btipling avatar Dec 15 '14 21:12 btipling

declare function diff_match_patch(): void;

Switching to this format removed errors, but it doesn't seem right.

btipling avatar Dec 15 '14 21:12 btipling

Hi! Yeah, the confusion here is around class vs. instance: DiffMatchPatch, as a type annotation, is the type of instances, not the type of the class value (i.e., the factory that produces instances, what TS calls the constructor function) itself. Your situation is analogous to this:

declare class Person { ... }
declare var p: Person = new Person(); // say
... new p() ... // error, can't call a constructor on p, it's just an instance of Person

A simple way to get the type of the class itself would be:

declare var diff_match_patch: typeof DiffMatchPatch;

From your example, I'm thinking this is what you want.

(More on typeof as a type annotation here.)

bhosmer avatar Dec 16 '14 00:12 bhosmer

...and you're right, constructor should be mentioned in the class docs. :)

bhosmer avatar Dec 16 '14 00:12 bhosmer

created pull request #197

tcoopman avatar Dec 16 '14 08:12 tcoopman

I still can't see any docs for how to document a constructor in a type declaration, am I missing something obvious?

glenjamin avatar Aug 04 '16 16:08 glenjamin

@glenjamin Do you mean like this:

declare module "my-module" {
  declare class Foo<X: number> {
    x: X;
    constructor(x: X): this;
  }
}

jamiebuilds avatar Aug 08 '16 23:08 jamiebuilds

Yep, couldn't see that in the docs anywhere - figured it out from some comments on here

glenjamin avatar Aug 09 '16 07:08 glenjamin