Coder Social home page Coder Social logo

flow2dts's Introduction

flow2dts

This tool aims to convert Flow declaration files to TypeScript declaration files. This means that the tool does not convert implementation code written in the Flow language, but solely library API signatures.

The primary goal is to provide up-to-date and high-quality TypeScript typings for React Native, which can be found in the DefinitelyTyped repository. These have historically been maintained in a manual fashion, which is labor intensive, have lagged behind React Native releases, and have been incomplete at best.

Limitations

Ideally the tool would be usable with any library implemented using the Flow language, however at this time the Flow compiler does not make the ability to generate declaration files available to the general public. (For React Native we rely on Facebook to generate these declaration files for us.) Until then, this tool should theoretically be able to convert manually maintained Flow declaration files, such as those in the flow-typed repository.

Even though we explicitly aim to convert declaration files only, it should theoretically be possible to generate TypeScript declaration files from Flow implementation code when all APIs are typed explicitly. This would likely require some alteration to this tool, but not in any significant way. (Please let us know if you end up making these changes.)

Acknowledgements

We would like to point out that while our project only targets declaration files, there are other active efforts that aim to convert Flow implementation code. Because of the different stated goals our project makes some different trade-offs than these; for instance, typically their aim is to convert one’s own project implemented in Flow to TypeScript far enough such that converting the remaining bits can be performed manually. Having said that, if the goal is to convert a codebase you should absolutely take a look at these:

React Native specific considerations

TODO Flesh this out.

  • Describe migration path.
  • Consider how to deal with different RN platforms, specifically how to use them in user projects.

Usage of the tool

flow2dts --root path/to/flow/inputs --out path/to/ts/outputs [FILES]

FILES can be a list of include patterns or exclude by prepending the ! operator.

Options:
  --version    Show version number                                     [boolean]
  --rootDir    The root directory of the Flow sources        [string] [required]
  --outDir     Where the TS sources should be written        [string] [required]
  --platform   Determines which platform specific files to include
                                 [string] [required] [choices: "ios", "android"]
  --cwd        The working directory from which to expand relative paths[string]
  --overrides  A file that exports a OverridesVisitor object used to provide
               project specific overrides where conversion cannot accurately be
               made                                                     [string]
  --help       Show help                                               [boolean]

Workbench

For the time being, examples of using the tool to convert React Native typings can be found in the workbench directory.

  • react-native: Contains Flow declaration dumps for React Native v0.63.3 and a recent main-line commit.
  • artsy-eigen: Contains the TypeScript sources of a OSS iOS application by Artsy Inc.. This application uses React Native v0.63.3 + TypeScript and thus serves as a good real-world test-bed.

Contributing

See the contributing documentation.

Security

See the security documentation.

License

This tool is available under the MIT license.

Trademarks

This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft trademarks or logos is subject to and must follow Microsoft's Trademark & Brand Guidelines. Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship. Any use of third-party trademarks or logos are subject to those third-party's policies.

flow2dts's People

Contributors

alloy avatar kelset avatar tido64 avatar zihanchen-msft avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

flow2dts's Issues

Don't store classes in intermediate variables

Consider the following examples:

Flow example

Libraries/Animated/src/nodes/AnimatedValue.js.flow

declare class AnimatedValue {}
declare module.exports: typeof AnimatedValue;

Libraries/Animated/src/AnimatedMock.js.flow

declare var AnimatedValue: typeof $7;
const $7 = require("./nodes/AnimatedValue");

declare var someFunction: (
  value: AnimatedValue,
) => void;

Correct TypeScript conversion

Libraries/Animated/src/nodes/AnimatedValue.d.ts

declare class AnimatedValue {}
default export AnimatedValue;

Libraries/Animated/src/AnimatedMock.d.ts

import AnimatedValue from "./nodes/AnimatedValue";

declare var someFunction: (
  value: AnimatedValue,
) => void;

ACTION REQUIRED: Microsoft needs this private repository to complete compliance info

There are open compliance tasks that need to be reviewed for your flow2dts repo.

Action required: 4 compliance tasks

To bring this repository to the standard required for 2021, we require administrators of this and all Microsoft GitHub repositories to complete a small set of tasks within the next 60 days. This is critical work to ensure the compliance and security of your microsoft GitHub organization.

Please take a few minutes to complete the tasks at: https://repos.opensource.microsoft.com/orgs/microsoft/repos/flow2dts/compliance

  • The GitHub AE (GitHub inside Microsoft) migration survey has not been completed for this private repository
  • No Service Tree mapping has been set for this repo. If this team does not use Service Tree, they can also opt-out of providing Service Tree data in the Compliance tab.
  • No repository maintainers are set. The Open Source Maintainers are the decision-makers and actionable owners of the repository, irrespective of administrator permission grants on GitHub.
  • Classification of the repository as production/non-production is missing in the Compliance tab.

You can close this work item once you have completed the compliance tasks, or it will automatically close within a day of taking action.

If you no longer need this repository, it might be quickest to delete the repo, too.

GitHub inside Microsoft program information

More information about GitHub inside Microsoft and the new GitHub AE product can be found at https://aka.ms/gim or by contacting [email protected]

Clean export

declare namespace $f2tExportDefaultRedirect {
  export const $f2tHidden_Value: $TypeOf<typeof $12>;
}
declare namespace $f2tExportDefault {
  export const Value: $TypeOf<typeof $f2tExportDefaultRedirect.$f2tHidden_Value>;
  export type Value = $TypeOf<typeof $f2tExportDefaultRedirect.$f2tHidden_Value>;
}

Generated code like this can be much more clear by having a hint file

Import as if es6 module export from default exported object

TS2614

Error:

workbench/outputs/ios/Libraries/Components/Pressable/useAndroidRippleForView.d.ts:5:10 - error TS2614: Module '"../../.."' >has no exported member 'View'. Did you mean to use 'import View from "../../.."' instead?
workbench/outputs/ios/Libraries/Components/Touchable/TouchableBounce.d.ts:7:10 - error TS2614: Module '"../../.."' has no >exported member 'Animated'. Did you mean to use 'import Animated from "../../.."' instead?

Reason: View and Animated are imported in index.d.ts, but they are not exported from index.d.ts

This is actually a little different in cause. The upstream Flow code also doesn’t separately export these. Instead, it appears that with Flow one can have import specifiers for entities that are actually properties of the default export object.

We should consider if we want to support this more generically long-term, but I suspect the implementation will be a little more involved than a simple fix and this issue also only comes up twice. In addition, these instance are actually importing these values differently than many other places in the codebase, so one could argue that these could just be changed in the upstream RN source too.

[need verification] Do `import typeof` right

When the module exports a value, import typeof NAME makes NAME its type
When the module exports a class, import typeof NAME makes NAME its constructor
So we don't need to care about if the module exports a value or a class, when we see import typeof X from 'Y', we generates

import X from 'Y'

and replace every X in the code to typeof X

But in index.js.flow, it exports

declare module.exports: {|
  get Button(): Button
|}

we needs to generate

export {Button}
declare const $f2tExportDefault: {
  Button: typeof Button
}
export default $f2tExportDefault;

Need to carefully make a decision.

Difference between RN's and DT's SyntheticEvent type

In RN’s upstream type, most of the properties are Maybe types. Whereas in DT’s React type they are all required properties. This means that a value with RN’s type cannot be assigned to a target that expects DT’s type.

I only came across 1 such case in Artsy’s codebase, which I solved locally with a utility type that removes all the Maybe variants. It is unclear if this issue structurally applies to RN projects or is more of an issue with e.g. Formik relying on HTML event types.

Generate a hint file for identifiers for workbench input

As alloy/flow2dts#24 said, if we know whether a identifier is a class, a type or a value, it would help us get rid of generating $TypeOf<typeof T> to make the code correct.

A new package is expected as a separate pass to generate this hint file. If the input is changed, execute this package to generate new hint files. Once hint files are ready, our transpiler can be updated to leverage on these files.

Convert type alias to interface?

TypeScript allows for declaration merging of interfaces, which appears to be something that people do to extend types for react-native-web, whereas this cannot be done with type aliases. So it might be preferable to convert to interfaces.

interface X { foo: string }
interface X { bar: string } // merge declaration
const x: X = { foo: "foo", bar: "bar" }

In case it makes things easier, perhaps as a first step, we could also create a temp type alias and use it to extend an empty interface with:

type $1 = { foo: string }
interface X extends $1 {}
interface X { bar: string } // merge declaration
const x: X = { foo: "foo", bar: "bar" }

Upstream local patches

Migration path from current DefinitelyTyped RN typings

This ticket describes the differences with the existing manually maintained DT typings and the migration path to these converted ones.

  • TypeScript does not have a build in way to deal with different files for different platforms. microsoft/TypeScript#21926

    • How can we offer distinctive sets of typings for iOS and Android (eg @types/react-native-ios, @types/react-native-android) and let the user configure them for their project?
    • Can DT handle this?
    • And can other DT packages that depend on RN use this too?
  • Many (all?) components are no longer class based, but rather function or even ‘abstract’ based. Because classes can be used as types in TS, there may be user code that refers to it that way but now needs to change to typeof View. This does not seem like an issue we need to resolve, as it’s simply not in line with reality. TS2749

  • Component props interfaces are exported, whereas upstream Flow code requires the user to do React.ElementProps<typeof View>. We currently export these separate props types as a migration convenience, but they are annotated as being deprecated.

    • There are many more component props interfaces still missing.
    • Should we add ElementProps to the React DT typings and is it correct that ElementProps does not include ref (as we use ComponentPropsWithoutRef of the React DT typings)?
  • Allow interface merging of RN NativeModules. These contain the user's own and 3rd party native modules and so should allow for the user to provide typings. f41628c

  • Style type param passed to StyleSheet.create<T>(…) needs to by a type alias, not an interface; because microsoft/TypeScript#15300 (comment). But also there's no longer a need to define the type upfront anymore (which perhaps was already no longer needed).

[TS2322] Component class with wider defaultProps typing

There seem to be only a few of these, one is here. Perhaps best to solve with an override.

import * as React from "react"

class Foo extends React.Component<{ mode?: null | undefined | ("dialog" | "dropdown") }> {
  static defaultProps: {
    // This supertype here makes it no longer match the React.ComponentClass interface,
    // which is used in React.ComponentType
    mode: string
    // This works
    // mode?: null | undefined | ("dialog" | "dropdown")
  }
}

type ExtractProps<X> = X extends React.ComponentType<infer P> ? P : never

type Props = ExtractProps<typeof Foo>
const props: Props = { mode: "dialog" }

React.ComponentClass is defined here.

Classes are not correctly exported in index.d.ts

In index.d.ts there are many exported items in this pattern:

import AccessibilityInfo$f2tTypeof from "./Libraries/Components/AccessibilityInfo/AccessibilityInfo";
declare type AccessibilityInfo = typeof AccessibilityInfo$f2tTypeof;
export { AccessibilityInfo$f2tTypeof as AccessibilityInfo };
declare const $f2tExportDefault: { AccessibilityInfo: AccessibilityInfo; };
export default $f2tExportDefault;

In AccessibilityInfo there is:

declare var AccessibilityInfo: { /* members */ };
declare const $f2tExportDefault: typeof AccessibilityInfo;

AccessibilityInfo is supposed to be both a value and a type,
but I suspect index.d.ts export it as value twice.

Here are AccessibilityInfo in @types/react-native:

export interface AccessibilityInfoStatic { ... }
export const AccessibilityInfo: AccessibilityInfoStatic;
export type AccessibilityInfo = AccessibilityInfoStatic;

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.