Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

specify type of a property #1498

Closed
coot opened this issue Mar 6, 2016 · 6 comments
Closed

specify type of a property #1498

coot opened this issue Mar 6, 2016 · 6 comments

Comments

@coot
Copy link

coot commented Mar 6, 2016

Currently this code will raise a syntax error (Unexpected token :):

function MyClass() {
 this.x: number = 1;
}

There are some workarounds:

function MyClass() {
  let x: number = this.x = 1;
}

or use ES6 classes

class MyClass {
  x: number;
  constructor() {
    this.x = 1;
  }
}

But when introducing flow to an existing code base, one might not want to rewrite all the code.

I tried to use this.x = (1: number) but this will not assure that the x property will be always of a number type. Another possible choice is to define an interface and type use it when MyClass is instantiated, but then one has to remember to do that, and interfaces are structural rather than nominal, like classes are.

Though it does not seem useful, it is only because the example is very simple. A real example in which one would like to specify type directly is when the property is a knockout observable which could hold only a specific type (knockout observables are functions with return a type T and which can set the stored value when given a parameter (of type T)).

@samwgoldman
Copy link
Member

I think the best solution to this issue is actually the solution to #452. What do you think?

@coot
Copy link
Author

coot commented Mar 6, 2016

@samwgoldman, could you be more specific, I don't see there anything that could help me here.

@avikchaudhuri
Copy link
Contributor

avikchaudhuri commented Mar 7, 2016

@coot I think what @samwgoldman means is that you could do something like the following in the future (module syntax):

function MyClass[this: { x: number }]() {
 this.x = 1;
}

@coot
Copy link
Author

coot commented Mar 8, 2016

Did I missed it in the docs? I think I haven't stumbled on how to specify type of this in functions.

@samwgoldman
Copy link
Member

No, it's not implemented. The linked issue is still open. My point is that solving that issue will also solve this one.

@calebmer
Copy link
Contributor

We recommend you use ES6 classes. Please let me know if you still have questions 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants