-
Notifications
You must be signed in to change notification settings - Fork 1.9k
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
way to extend/override flow/lib types #396
Comments
Why not edit the lib files in place and rebuild Flow? You could pull request your modifications eventually. |
@popham why not to check types using your eyes? +1 for topic |
I propose the following syntax for overriding flow types: Firstly, we need a way to extend types that are not classes. The syntax is obviously Object spread:
Next, it should be possible to reassign a declaration:
|
What's wrong with In these situations, my gut says that you should put the Flow libraries in your project somewhere under version control. When you need to override something, edit it. Any external libraries that you've incorporated into your project will be validated against your environment specification (the version controlled library files). (Corollary: If you're making a library, work against Flow's unaltered libraries.) I guess this could be facilitated by moving Flow's libraries to a separate repo so that users could shallow clone them into projects? The counterargument goes: "I want my project to see updates to Flow's libraries." I say, "You want your environment specification to change at the whim of Flow's maintainers? You shouldn't." Sure Flow's libraries are still immature, but I think that the proper tact is to help improve them instead of implementing override support (this is low-hanging fruit for non-maintainers). Eventually they'll stabilize and track some ideal environment as it evolves with JS, popularity of Node, popularity of IE8, etc.
|
@nmn For your A/B example, you should be able to use intersection types: |
Whoops. Thanks @samwgoldman. |
@samwgoldman Thanks for the clarification. I'm still wrapping my head around what intersections do. This makes a ton of sense. So I guess the only part is to be able to override types. While I don't think there's anything wrong with
And I use it already. It would be nice to be able to add/modify properties on a type for specific environments. By the way, I was wondering if the
Is that any different from defining it like so:
Also, as you mentioned above you can do Just to clarify, I'm not hating on the class syntax (which can be a little confusing), but just trying to understand some of the subtleties of the type system. |
Second part first. The difference is that you cannot First part. The scope of a
|
@popham If i'm not wrong, this is what I think: (Second part first) while you would generally do:
now you can do:
As for being able to use the new keyword, instead of using Now to the first part. At first I really liked the idea of getting rid of global type definitions. |
I'm having trouble understanding you. I've used Flow, I've used React, but I've never used them together, so I'll probably be a little sloppy. The following are coherent, independent narratives:
class MyComponent extends ReactComponent {
someProp: string;
constructor() {
super(...);
this.someProp = "MyComponent";
}
}
class YourComponent extends ReactComponent {
someProp: string;
constructor() {
super(...);
this.someProp = "YourComponent";
}
} Now I can create a function that rejects non-ReactComponents and rejects ReactComponents without a function printSubComponent(sc: ReactSubComponent): void {
console.log(sc.someProp);
}
printSubComponent(new MyComponent());
printSubComponent(new YourComponent());
printSubComponent({someProp: "a string"}); // No good. The object is not an instance of `ReactComponent`.
printSubComponent(new ReactComponent()); // No good. This instance is missing the `someProp` property. This subcomponent is just a type. If I try to create an instance, I'll get an error:
// Flow doesn't have access to this class.
// It is injected into the JS environment *somehow*.
class ReactSubComponent extends ReactComponent {
constructor() {
super(...);
this.someProp = "ReactSubComponent"; // or `15` or `{randomProperty: ["three"]}`
}
} I'm going to attach this class to the global scope of my environment; the identifier declare class ReactSubComponent extends ReactComponent {
someProp: any;
} This declaration is not type checked by Flow; it is inside a library file referenced from the var sc = new ReactSubComponent();
class MySubSubComponent extends ReactSubComponent {...} |
You're right about this. ReactSubComponent is just a type so you can't use it in your code at all! but you can use it to annotate classes you may define:
|
What is the preferred method for dealing with errors like this, when the built-in typedef is just incomplete?
|
@STRML that's a problem with the type definitions library. You'll have to manually override the type definition for http. Maybe something like: var http: CustomHttpType = require('http'); |
Is there any way to do it globally, say in an interfaces file, so I don't
|
In node it's very common to promisify the fs module with Bluebird, which adds methods like declare module fs extends fs {
declare function openAsync(filename: string, mode: string): Promise<number>;
} |
👍 to this suggestion. It would really help when a definition file is just missing a few methods, rather than having to copy/paste the whole thing from the repo and edit. |
👍 here, as well. My use-case is that I wish to Flow-typecheck my tests (or rather, to flip that on its' head, I wish to typecheck my library, using my tests.); but I always use Chai / should.js style assertions when not targeting ancient engines like IE6.
Basically, while I understand some of the above arguments against such things (hell, this back-and-forth goes back more than a decade, in some ways.), I'd say it boils down to … “Are you really telling me I simply can't use Flow, if my library extends another system's prototypes?” Whether that's extending I really, really think Flow should include a mechanism to support it, even if it's felt necessary to add warnings in the documentation that it's considered an anti-pattern, or exceptionally dangerous, or … |
another reason to consider this is that one could generate flow type definitions from WebIDL (there's a lot of |
Trying to add flow to my library that makes extensive use of As @ELLIOTTCABLE mentioned, prototype extension is fundamental and should not make the project incompatible. These are the types of errors I get: 41: initialState.should.be.an('object')
^^^^^^ property `should`. Property not found in
41: initialState.should.be.an('object')
^^^^^^^^^^^^ object type |
@popham (I'm new to Flow, so bear with me.) Seems to me that there's an obvious example of why this is a much needed feature - jQuery plugins. Type definition for jQuery is huge and looks like this: declare class JQueryStatic {
(selector: string, context?: Element | JQuery): JQuery;
// ...
}
declare class JQuery {
addClass(className: string): JQuery;
// ...
}
declare var $: JQueryStatic; When I use a jQuery plugin, e.g. Highcharts, it is added as a new method on the const chart = $('#myCoolChart', contextNode).highcharts({ ... }); There's no |
Yeap. Decided not to use flow because of issues like this: element.style.msOverflowStyle = 'scrollbar';
// Error:(12, 15) Flow: property 'msOverflowStyle'. Property not found in CSSStyleDeclaration. Whenever flow sees property it doesn't know, it throws an error. Is there a way to work around this? |
(element.style: any).msOverflowStyle = 'scrollbar'; |
@vkurchatkin thank you, it worked! |
For things like React, it'd be great to be able to extend the core types temporarily. For example, |
Not sure it's intentional, but this workaround seems to be working for me. Say, I have a case for
|
Yeah, that works well for certain globals. But if you want to e.g. change the type of a field on |
I am not able to use chai and chai-spies with Flow for that very reason. Just no way to tell that |
For anyone coming into this looking for a solution, @nmn's post (#396 (comment)) earlier is now possible. For example, declare interface Document extends Document {
mozHidden: boolean,
msHidden: boolean,
webkitHidden: boolean,
} |
That still does not work with custom types. declare interface Some {
a: string
}
declare interface Some extends Some {
b: string
}
|
Any idea on when (if ever) flow will support extending existing modules? @deecewan makes a good point and now we are facing the same issue with forwardRef for react ... |
I came up with the following solution to my // @flow
import Vue from 'vue'
import type { Axios } from 'axios'
import type { Store } from 'vuex'
import type Router from 'vue-router'
import type { State } from '~/types/vuex'
import type { NuxtAuth } from '~/types/nuxt-auth'
/**
* Represents our extended Vue instance.
*
* We just use the annotations here, since properties are already injected.
* You will need to add new annotations in case you will extend Vue with new
* plugins.
*/
export default class CustomVue extends Vue {
$auth: NuxtAuth
$axios: Axios
$router: Router
$store: Store<State>
} And then just using it like so: // @flow
import Component from 'nuxt-class-component'
import CustomVue from '~/logics/custom-vue'
@Component()
export default class Index extends CustomVue {
logout () {
this.$auth.logout() // type of `logout()` is defined in `NuxtAuth`
}
} And it works! |
@sobolevn thank you for the suggestion ! The only 'drawback' is now you have to import 'custom-vue' instead of directly importing 'vue', which might (?) cause issues in plugins relying on the import of the actual library. In my case, I had to deal with 'react' and I think JSX would not be properly understood if I would rename the 'react' library itself. What I have ended up doing (in case someone else come to this post looking for the same) is to wrap the required function within a 'typed' version of it. Fortunately, in my case the function I was willing to add is forwardRef from React, which is already in the pipeline to be added, so I could refer to the proposed typing from #6103. In my case the definition looks like: // $FlowFixMe
import {forwardRef} from 'react';
export function typedForwardRef<Props, ElementType: React$ElementType>(
render: (props: Props, ref: React$Ref<ElementType>) => React$Node
): React$ComponentType<Props> {
return forwardRef(render);
} |
I have meet this issue from the very first beginning of trying to introduce flow into my existing project,and this problem scares me away, and I do not like TypeScript too, so I think maybe I can only keep checking types using my eyes 🤷♂️ |
I've got a related use-case: I'd like to force all interactions with DOM APIs to enforce sanitization of untrusted content. I can declare |
The only solution (actually dirty hack) advised so for (using --no-flowlib) does not work because the modules written this way can't be redistributed. |
Maybe the core team members have moved to TypeScript? |
I found creating new types using intersections to be a decent way to extend existing, thirdparty types. |
I was trying to use react hooks in react-native but RN only support flow |
I'm looking to create some typings for a testing library of mine, Must.js, that extends |
Once again after more than a year I am looking into useful way to add strong typing ... I just don't like TypesScript, and enabling intellisense for plain JS in VS code is not working properly yet |
Just try TypeScript. Evidently Microsoft cares more about community than Facebook. |
It's now possible to override custom (user-land) types with the spread type operators. This is a huge win for me (finally!). Has anybody tried overriding built-in types this way? |
@unscriptable What do you mean by "override custom type"? Spread creates new type like values spread creates new object. There is no mutating happen. |
I think somebody needs to write a blog post about how spreads can be used in place of type extension. I can see a few use cases (listed in this thread) that I can’t figure out how a spread type would help. One way of formulating a motivating use case is this: Given a global type like MouseEvent, how might I use a spread so Flow doesn’t complain when I try to access a new property that is not yet added to the spec definition? And what if the MouseEvent is defined as a class rather than an object? |
Built-in node.js type declarations are still far from being complete, and filling the missing parts is very cumbersome as Flow doesn't allow to overwrite single modules.
For instance, if I want to fill in some gaps in HTTP types, I have to use flow with
--no-flowlib
flag, which forces me to copy all the remaining built-in interfaces to my project.Although such workaround works for now, it's unmaintainable in the longer term, and not obvious to newcomers.
Would it be a problem to make custom declarations override the default ones?
The text was updated successfully, but these errors were encountered: