Coder Social home page Coder Social logo

knisterpeter / react-to-typescript-definitions Goto Github PK

View Code? Open in Web Editor NEW
238.0 2.0 15.0 2.98 MB

Create typescript definitions files (d.ts) from react components

License: MIT License

JavaScript 17.60% TypeScript 82.40%
react typescript proptypes typescript-definitions parser

react-to-typescript-definitions's People

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  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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

react-to-typescript-definitions's Issues

Failed to lookup identifier for imported PropTypes

Hey can this be handled, would be awesome!
Version using: 2.0.0, also reproduced on 3.0.1

Console output
/home/damend/IdeaProjects/react-ui/src/components/typography/severity-blocks/severity-text/severity-text.jsx Failed to lookup identifier
Line 7: SeverityText.propTypes = {
Line 8: severity: PropTypes.oneOf(componentSeveritiesTypesConfig).isRequired,
Line 9: text: PropTypes.string.isRequired,

File A:

import { componentSeveritiesTypesConfig } from 'components/configs/component-severities-types-config';
import React from 'react';
import * as PropTypes from 'prop-types';
import css from './severity-text.module.scss';

export const SeverityText = ({ severity, text }) => {text};
SeverityText.propTypes = {
severity: PropTypes.oneOf(componentSeveritiesTypesConfig).isRequired,
text: PropTypes.string.isRequired,
};

File: component-severities-types-config

export const componentSeveritiesTypesConfig = ['', 'info', 'error', 'warn', 'success'];

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Location: package.json
Error type: The renovate configuration file contains some invalid settings
Message: Invalid configuration option: author, Invalid configuration option: ava, Invalid configuration option: bin, Invalid configuration option: files, Invalid configuration option: license, Invalid configuration option: main, Invalid configuration option: name, Invalid configuration option: nyc, Invalid configuration option: packageRules[0].@knisterpeter/standard-tslint, Invalid configuration option: packageRules[0].@types/babel-generator, Invalid configuration option: packageRules[0].@types/diff, Invalid configuration option: packageRules[0].@types/execa, Invalid configuration option: packageRules[0].@types/node, Invalid configuration option: packageRules[0].@types/prop-types, Invalid configuration option: packageRules[0].@types/react, Invalid configuration option: packageRules[0].ava, Invalid configuration option: packageRules[0].babel-core, Invalid configuration option: packageRules[0].babel-preset-es2015, Invalid configuration option: packageRules[0].babel-register, Invalid configuration option: packageRules[0].chokidar-cli, Invalid configuration option: packageRules[0].codecov, Invalid configuration option: packageRules[0].coveralls, Invalid configuration option: packageRules[0].diff, Invalid configuration option: packageRules[0].execa, Invalid configuration option: packageRules[0].nyc, Invalid configuration option: packageRules[0].prettier, Invalid configuration option: packageRules[0].prop-types, Invalid configuration option: packageRules[0].react, Invalid configuration option: packageRules[0].rimraf, Invalid configuration option: packageRules[0].standard-version, Invalid configuration option: packageRules[0].tslint, Invalid configuration option: packageRules[0].typescript, Invalid configuration option: packageRules[1].astq, Invalid configuration option: packageRules[1].babel-generator, Invalid configuration option: packageRules[1].babylon, Invalid configuration option: packageRules[1].chalk, Invalid configuration option: packageRules[1].dts-dom, Invalid configuration option: packageRules[1].get-stdin, Invalid configuration option: packageRules[1].meow, Invalid configuration option: packageRules[1].pascal-case, Invalid configuration option: packageRules[1].strip-ansi, Invalid configuration option: prettier, Invalid configuration option: renovate, Invalid configuration option: scripts, Invalid configuration option: types, Invalid configuration option: version

An in-range update of @knisterpeter/standard-tslint is breaking the build 🚨

Version 1.3.0 of @knisterpeter/standard-tslint just got published.

Branch Build failing 🚨
Dependency @knisterpeter/standard-tslint
Current Version 1.2.0
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As @knisterpeter/standard-tslint is β€œonly” a devDependency of this project it might not break production or downstream projects, but β€œonly” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this πŸ’ͺ


Status Details
  • ❌ continuous-integration/travis-ci/pr The Travis CI build could not complete due to an error Details
Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

type definitions without module

Hi,

I have multiple Scenarios and not sure if your library support them:

  • I would like to generate dts files for multiple JSX with single command
  • I would like to generate index.d.ts file for each widget, but I do not want to declare module.

Do you have and examples how I can achieve this with react2dts?

Thanks in advance!

Artyom

Do not fail if no export is found

This is a bug (breaking change) from 0.11/0.12/0.13.
It should be possible to provide a file without react classes or propType definitions without failure.

Dependency security issue

npm audit reports dependency issue

The package has a fixed version dependency of "astq": "2.3.6, which in chain has dependency to an outdated version of lodash.

Triple slash directive is broken #469

I saw that #469 issue was resolved by #472 and then changed by #482

For some reason I am now getting the error

[ts]
JSX element type 'MyComponent' is not a constructor function for JSX elements.
  Property 'setState' is missing in type 'MyComponent'.
[ts] JSX element class does not support attributes because it does not have a 'props' property.

The generated .d.ts file looks like the following:

declare module '@mycomponents/components' {
    import * as React from 'react';

    export interface MyComponentProps {
        children: React.ReactNode;
    }

    export default class MyComponent extends React.Component<MyComponentProps, any> {
        render(): JSX.Element;
    }
}

If I add

/// <reference types="react" />

Then this solves this issue.

undefined prop name for nested props

Hey

it seems that library doesn't pick name of prop if the prop is defined as string literal inside .shape

example:

SomeComponent.propTypes = {
  action: PropTypes.shape({
    'aria-label': PropTypes.string,

it generated following types:

export interface SomeComponentAction {
    undefined?: string;

could you please confirm that this is a bug? if so you could maybe point me out where the bug might be? I'm keen to fix this πŸ™‚

thanks!

Jsdoc is not generated

First of all great tool and we do use it with pleasure every day!

Used version: 2.0.0

applying generateFromFile(null, filePath, { babylonPlugins: ['optionalChaining'] })

on (breaking the markdown formatting)

`/**

  • A component to setup
  • @param {String} basename - base url for react
  • @param {String} baseUrl - base url for API
  • @param {Object} translations - {en: JSON, de: JSON} json translation English and German languages
  • @param {Node} children - content to render inside the component(should not be passed as a prop)
  • @param {String} homeUrl - url to home page of application, used to redirect from Error page, etc.
  • @param {String} errorPagePath - path to error page within your React application
  • @param {Function} getPlatformContextData
  • */
    export function MyComp({
    ...
    }
    MyComp.defaultProps = {
    forceSentryIoToEnable: false,
    };

MyComp.propTypes = {
children: PropTypes.node.isRequired,
basename: PropTypes.string.isRequired,
baseUrl: PropTypes.string.isRequired,
homeUrl: PropTypes.string.isRequired,
errorPagePath: PropTypes.string.isRequired,
getPlatformContextData: PropTypes.func.isRequired,
// eslint-disable-next-line react/forbid-prop-types
translations: PropTypes.object.isRequired,
forceSentryIoToEnable: PropTypes.bool,
};`

Does not preserve the code comments, but generates

`
import * as React from 'react';

export interface MyComp{
children: React.ReactNode;
basename: string;
baseUrl: string;
homeUrl: string;
errorPagePath: string;
getPlatformContextData: (...args: any[])=>any;
translations: Object;
forceSentryIoToEnable?: boolean;
}

export const MyComp: React.FC;`

Any idea? I do not see there is a test for JSdoc, yet in the project.

don't generate types for wrapped components

Hey

we have a few components that are wrapped into injectIntl at export statement

function SomeComponent() { .. }

export default injectIntl(SomeComponent);

and library fails to generate types for them, it provides empty content:

import * as React from 'react';

do you know how we could workaround this? otherwise could you please point out me in the code where I could fix that?

An in-range update of @types/react is breaking the build 🚨

Version 16.0.17 of @types/react was just published.

Branch Build failing 🚨
Dependency @types/react
Current Version 16.0.16
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

@types/react is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push The Travis CI build failed Details

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Stateless functional components

Right now we type stateless functional components as functions.
This means, that children are not included in the type definition by default.

We could do something like

export type Component = SFC<ComponentProps>;

What do you think?

Failed to lookup shape properties

Hi guys,

I have noticed that the library is returning any for a property when propTypes are imported from some other component. Here is an example:

// ComponentOne.jsx

ComponentOne.propTypes = {
  myProp: PropTypes.string,
};

// ComponentTwo.jsx

ComponentTwo.propTypes = {
  componentOneProps = PropTypes.shape(ComponentOne.propTypes),
}

Output:

export interface ComponentTwoProps {
  componentOneProps?: any;
}

Console output:

Failed to lookup shape properties
Line n:   componentOneProps: PropTypes.shape(ComponentOne.propTypes),

Is it possible to get the actual type from the imported component?

Expected:

export interface ComponentTwoComponentOneProps {
  myProp?: string;
}

export interface ComponentTwoProps {
  componentOneProps?: ComponentTwoComponentOneProps;
}

version: 3.1.0

Thank you!

Return empty prop list when I try to use propTypes from other components

Hello! For my design system I use third-part UI module for react-native.

I need to use propTypes from 'react-native-paper' in my components, so I just set propTypes = component.propTypes. But.

my Checkbox.jsx
image

Source of CheckboxModule.Android prop types from 3rd party:

image

Am I doing something wrong or react-to-typescript-definitions doesn't support that 'wired' magic like my project -> module js component -> they .d.ts -> my component?

Examples:

Js Checkbox Component from 3rd part:
https://github.com/callstack/react-native-paper/blob/master/src/components/Checkbox.js

.d.ts file:
https://github.com/callstack/react-native-paper/blob/master/typings/components/Checkbox.d.ts

How to write props to work with react-to-typescript-definitions

Currently this not works in typescripted project.

https://github.com/nfq-eta/react-router4-with-layouts/blob/59e8917c0ba183e7ab4c5e7fd210ea74ccc03696/src/index.jsx

import React from 'react';
import PropTypes from 'prop-types';
import { Route as ReactRoute } from 'react-router-dom';

export const Route = (initProps) => {
  const { component, layout, ...rest } = initProps;
  let routeComponent = props => React.createElement(component, props);

  if (layout) {
    routeComponent = props =>
      React.createElement(layout, props, React.createElement(component, props));
  }

  return <ReactRoute {...rest} render={routeComponent} />;
};

Route.propTypes = {
  layout: PropTypes.oneOfType([
    PropTypes.func,
    PropTypes.node,
  ]),
  component: PropTypes.oneOfType([
    PropTypes.func,
    PropTypes.node,
  ]).isRequired,
};

Route.defaultProps = {
  layout: [],
};

https://unpkg.com/[email protected]/dist/index.d.ts

declare module 'react-router4-with-layouts' {
    export type RouteLayout = (...args: any[])=>any | React.ReactNode;

    export type RouteComponent = (...args: any[])=>any | React.ReactNode;

    export interface RouteProps {
        layout?: RouteLayout;
        component: RouteComponent;
    }

    export function Route(props: RouteProps): JSX.Element;

}

Got the error:

Error:(25, 28) TS2322: Type '{ path: "/demo"; component: typeof DemoPage; layout: typeof DefaultLayout; }' is not assignable to type 'IntrinsicAttributes & RouteProps'.
  Type '{ path: "/demo"; component: typeof DemoPage; layout: typeof DefaultLayout; }' is not assignable to type 'RouteProps'.
    Types of property 'layout' are incompatible.
      Type 'typeof DefaultLayout' is not assignable to type '((...args: any[]) => any) | undefined'.
        Type 'typeof DefaultLayout' is not assignable to type '(...args: any[]) => any'.

An in-range update of dts-dom is breaking the build 🚨

Version 0.1.20 of dts-dom just got published.

Branch Build failing 🚨
Dependency dts-dom
Current Version 0.1.18
Type dependency

This version is covered by your current version range and after updating it in your project the build failed.

dts-dom is a direct dependency of this project this is very likely breaking your project right now. If other packages depend on you it’s very likely also breaking them.
I recommend you give this issue a very high priority. I’m sure you can resolve this πŸ’ͺ

Status Details
  • ❌ coverage/coveralls Coverage pending from Coveralls.io Details
  • ❌ continuous-integration/travis-ci/push The Travis CI build could not complete due to an error Details

Commits

The new version differs by 20 commits.

  • 3d1e235 0.1.20
  • d83d8c3 Fix error
  • 35712a3 0.1.19
  • 6125304 Merge pull request #28 from NewFuture/patch-1
  • f0080be fixed optional parameters in method
  • e27ec01 Merge pull request #24 from leonard-thieu/fix-bare-function-signatures
  • a12cc70 Remove separate type for interface members.
  • b3dcc15 CallSignature should extend DeclarationBase.
  • 651df9d Rename printObjectTypeMembers() to printInterfaceMembers().
  • d121aa1 Add separate type for interface members.
  • b917ab1 Add separate type for call signatures.
  • 54c47f8 Merge pull request #22 from leonard-thieu/fix-readme
  • aae4386 Merge pull request #25 from leonard-thieu/generic-type-aliases
  • 5cf1e82 Merge pull request #23 from leonard-thieu/add-object-primitive
  • de3761e Add support for generic type aliases.

There are 20 commits in total.

See the full diff

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

Not recognizing back quotes as quotes

Not sure if this is a bug or intended behavior but wanted to call out

type: oneOf([PRIMARY, SECONDARY]),
creates: type?: any | any;

vs

type: oneOf(['PRIMARY', 'SECONDARY']),
create: type?: "PRIMARY" | "SECONDARY";

Nested complex types fall back to any

In our project some types fall back to any (error message: Failed to infer PropType; Fallback to any). It seems that nested complex types could be a cause of those issues, e.g.:

static propTypes = {
  foo: React.PropTypes.arrayOf(React.PropTypes.shape({
    bar: React.PropTypes.string,
    baz: React.PropTypes.string
  }))
}

Enable optional chaining in babylon parser

Hey

I try to use this great library for my library of components and in some of them we use optional chaining feature and react-to-typescript-definitions fails to generate types for them.

I checked code and found that to fix the issue we just need add 'optionalChaining', here: https://github.com/KnisterPeter/react-to-typescript-definitions/blob/master/src/index.ts#L134

I would love to submit PR but I can't push, don't have permissions.
➜  react-to-typescript-definitions git:(allow-optionalChaining) git push origin allow-optionalChaining  
ERROR: Permission to KnisterPeter/react-to-typescript-definitions.git denied to dozortsev.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

@KnisterPeter how could we handle that? πŸ™

namespaces for components

Hey

we have components that expose some props following way:

<Component type={Component.Type.FOO} />
                           ^^^^

this is done in following way:

// in Component.js file

const Component = (props) => {
 ...
}

const Type = {
 FOO: 'foo',
 BAR: 'bar',
 ..
}

Component.Type = Type;

export default Component;

if TypeScript would transpile such file it would create namespace for called Component:

// in Component.d.ts file

declare namespace Component {
    var Type: {
        FOO: string;
        BAR: string;
    };
}
export default Component;

while react-to-typescript-definitions ignore them at all or creates type:

export type ComponentType = "foo" | "bar" ;

export interface ComponentProps {
 ..
}

declare const Component: React.FC<ComponentProps>;

export default Component;

by ComponentType is not accessible anyhow if when you import component:

import { Component } from 'library-of-components;

Component.ComponentType
            ~~~~~~~~~~

is it possible somehow to work access ComponentType? or is it possible archive creation of namespace e.g by tweaking components code?

Read from file instead of stdin

It's not easy for example add some script to npm script tag to autogenerate typings after eatch build. And solution like "cat ... | ... > ...." is not cross platform :(

Feature request: Support preact

To support preact the generated typings should be

declare module 'component/button' {
    import {Component} from 'preact';

    export interface ButtonProps {
        onClick?: (...args: any[])=>any;
    }

    export default class Button extends Component<ButtonProps, any> {
        render(): JSX.Element;
    }
}

instead of

declare module 'component/button' {
    import * as React from 'react';

    export interface ButtonProps {
        onClick?: (...args: any[])=>any;
    }

     export default class Button extends React.Component<ButtonProps, any> {
    }
}

Error on trying to catch a type-resolving error

Hi,

the generator throws an error when it tries to catch an expected error on resolving a prop-type.
The error occurs in function printErrorWithContext:

TypeError: Cannot read properties of undefined (reading 'substring')
at printErrorWithContext (MY_REPO/node_modules/react-to-typescript-definitions/dist/src/types.js:202:75)
at Object.get (MY_REPO/node_modules/react-to-typescript-definitions/dist/src/types.js:53:13)
at MY_REPO/node_modules/react-to-typescript-definitions/dist/src/typings.js:212:30
at Array.forEach ()
at createPropTypeTypings (MY_REPO/node_modules/react-to-typescript-definitions/dist/src/typings.js:211:9)
at createExportedTypes (MY_REPO/node_modules/react-to-typescript-definitions/dist/src/typings.js:154:9)
at MY_REPO/node_modules/react-to-typescript-definitions/dist/src/typings.js:86:13
at Array.forEach ()
at createTypings (MY_REPO/node_modules/react-to-typescript-definitions/dist/src/typings.js:80:20)
at generateFromAst (MY_REPO/node_modules/react-to-typescript-definitions/dist/src/index.js:113:40)

For my understanding, following line of the function seems to result in undefined: const errorLine = lines[e.loc.start.line - 1];

For reproducing the error:
In my case, I have a kind of hacky oneOf-proptype, which generates its allowed values only for runtime:

const STATE_COLORS = {
  red: '#770000',
  green: '#008700',
  blue: '#4040F0',
  // Many more colors contained...
};

...

propTypes = {
  state_color: PropTypes.oneOf(Object.keys(STATE_COLORS)).isRequired
}

Of cource, the kind of "inline code" for the PropTypes.oneOf() function is not resolvable by the generator.
And therefor the generator calls printErrorWithContext - which is perfectly fine.

But the function should not throw/crash itself.
I would expect that the final generated type for my prop state_color is "any" (and that there are related log outputs by the generator).

--

Using package version 3.1.1

Fallback to any for `oneOf` with bound identifier

When passing the following source to any of the public methods

import React from 'react';

const fooOrBar = ['foo', 'bar'];

export default class SomeComponent extends React.Component {
   static propTypes = {
     someEnum: React.PropTypes.oneOf(fooOrBar)
   };
}

an error is logged, but not thrown:

Failed to infer PropType; Fallback to any
TypeError: Cannot read property 'map' of undefined
    at getEnumValues (~/node_modules/react-to-typescript-definitions/dist/src/types.js:105:22)
    at getComplexType (~/node_modules/react-to-typescript-definitions/dist/src/types.js:72:31)
    at Object.get (~/node_modules/react-to-typescript-definitions/dist/src/types.js:16:27)
    at ~/node_modules/react-to-typescript-definitions/dist/src/typings.js:67:30
    at Array.forEach (native)
    at createPropTypeTypings (~/node_modules/react-to-typescript-definitions/dist/src/typings.js:66:9)
    at ~/node_modules/react-to-typescript-definitions/dist/src/typings.js:35:17
    at Array.forEach (native)
    at Object.createTypings (~/node_modules/react-to-typescript-definitions/dist/src/typings.js:26:20)
    at generateFromAst (~/node_modules/react-to-typescript-definitions/dist/src/index.js:56:22)

All propTypes result to any, if PropTypes instead of React.PropTypes is used

Currently all propTypes default to any, if the following syntax is used instead of React.PropTypes:

import React, {PropTypes} from 'react';
...

    static propTypes = {
        className: PropTypes.string,
        component: PropTypes.string,
        renderOptions: PropTypes.object,
        children: PropTypes.element,
        order: PropTypes.string,
        source: PropTypes.string
    };

The culprit is in https://github.com/KnisterPeter/react-to-typescript-definitions/blob/master/index.ts#L155-L157

In the mentioned example above the node.type is still a MemberExpression, but the node.object.type is Identifier and the node.object.name is PropTypes

using v0.11.1

No typings generated if module exports object

Input:

import * as React from 'react';

const Component = ({optionalAny}) => <div />;
Component.propTypes = {
	optionalAny: React.PropTypes.any,
};

const Component2 = () => <div />;

export { Component, Component2 };

Expected output:

declare module 'component' {
  export interface ComponentProps {
    optionalAny?: any;
  }

  export function Component(props: ComponentProps): JSX.Element;

  export function Component2(): JSX.Element;
}

Actual output:

declare module 'component' {
}

Bindings to React.PropTypes should be resolved

react-to-typescript-definitions fails to resolve bindings to React.PropTypes members,
requiring authors to use React.PropTypes member expressions throughout:

import * as React from 'react';

// dereferencing propTypes
{
  playing: React.PropTypes.bool 
}
// yields typings
{
  playing?: boolean 
}
import {PropTypes} from 'react';

// named import propTypes
{
  playing: PropTypes.bool 
}
// yields any
{
  playing?: any 
}
import {PropTypes as types} from 'react';

// (re)name import propTypes
{
  playing: types.bool 
}
// yields any
{
  playing?: any 
}

Default classes without name are failing

This component fails with

import {createElement, Component, PropTypes} from 'react';

export default class extends Component {

    static propTypes = {
        onClick: PropTypes.func
    };

    render() {
        var children = props.children || 'Button';
        var onClick = props.onClick || (() => undefined);
        return (
            <button className="button" onClick={onClick}>
                {children}
            </button>
        );
    }
}
patternlib_1  | > node ./bin/create-typings
patternlib_1  | 
patternlib_1  | /patternplate/bin/create-typings.js:18
patternlib_1  | 			throw err;
patternlib_1  | 			^
patternlib_1  | 
patternlib_1  | TypeError: Cannot read property 'name' of null
patternlib_1  |     at /patternplate/node_modules/react-to-typescript-definitions/dist/src/typings.js:210:58
patternlib_1  |     at Array.map (native)
patternlib_1  |     at getComponentNamesByStaticPropTypeAttribute (/patternplate/node_modules/react-to-typescript-definitions/dist/src/typings.js:210:20)
patternlib_1  |     at Object.createTypings (/patternplate/node_modules/react-to-typescript-definitions/dist/src/typings.js:22:91)
patternlib_1  |     at generateFromAst (/patternplate/node_modules/react-to-typescript-definitions/dist/src/index.js:63:22)
patternlib_1  |     at generateFromSource (/patternplate/node_modules/react-to-typescript-definitions/dist/src/index.js:55:12)
patternlib_1  |     at Object.generateFromFile (/patternplate/node_modules/react-to-typescript-definitions/dist/src/index.js:25:12)
patternlib_1  |     at writeTypings (/patternplate/bin/create-typings.js:9:14)
patternlib_1  |     at Promise.all.paths.map.pathName (/patternplate/bin/create-typings.js:13:51)
patternlib_1  |     at Array.map (native)
patternlib_1  | 

Dependency deprecation warning: babel-preset-es2015 (npm)

On registry https://registry.npmjs.org, the "latest" version (v6.24.1) of dependency babel-preset-es2015 has the following deprecation notice:

πŸ™Œ Thanks for using Babel: we recommend using babel-preset-env now: please read babeljs.io/env to update!

Marking the latest version of an npm package as deprecated results in the entire package being considered deprecated, so contact the package author you think this is a mistake.

Affected package file(s): package.json

If you don't care about this, you can close this issue and not be warned about babel-preset-es2015's deprecation again. If you would like to completely disable all future deprecation warnings then add the following to your config:

"suppressNotifications": ["deprecationWarningIssues"]

error TS2324: Property 'children' is missing in type

I tried to compile this

import React, { Component } from 'react'
import classNames from 'classnames'

class Button extends Component {

  buttonTypeRender(){
    let style = 'button'
    let props = this.props
    style += ` ${classNames(props)}` + ` ${props.className}`
    if (props.type === 'link')
      return <a {...props} className={style} href={this.props.to}>{this.props.children}</a>
    else
      return <button {...props} className={style} type={props.type} desabled={this.props['is-disabled']}>{this.props.children}</button>
  }

  render () {
    return this.buttonTypeRender()
  }

}

Button.propTypes = {
  children: React.PropTypes.any.isRequired,
  type: React.PropTypes.oneOf(['submit', 'button', 'link', '']),
  className: React.PropTypes.string,
  to: React.PropTypes.string
}

Button.defaultProps = {
  type: 'link',
  className: '',
  to: '#'
}

export default Button

The result was this:

declare module 'bulma-react' {
    import * as React from 'react';

    export interface ButtonProps {
        children: any;
        type?: any;
        className?: string;
        to?: string;
    }

    export default class Button extends React.Component<ButtonProps, any> {
    }
}

Which seems fine to me but when I did a little test I couldn't compile it

/// <reference path="../tsd.d.ts" />
/// <reference path="../../react-bulma.d.ts" />


import {Component} from "react";
import Button from "bulma-react";

class BulmaApp extends Component<any, any> {
    render(){
        return (<Button>test</Button>);
    }
}

I got

?>tsc bulma-react-tests.tsx --jsx react --pretty

10         return (<Button>test</Button>);
                   ~~~~~~~~

bulma-react-tests.tsx(10,17): error TS2324: Property 'children' is missing in type 'IntrinsicAttributes & IntrinsicClassAttributes<Button> & ButtonProps & { children?: ReactElement<...'.

I'm using typescript 1.8.2.
Am I missing something here?

Improve error reporting

Currently an error including stack is logged if type processing fails.
It is not trivial to report correct errors to the user and continue processing the next types.

Related to #246

Generating a single type definition file for non-Typescript components

I have a library of react components which are all written in plain JS using the PropTypes library.

I'd like to use this tool to generate a single typescript definition file so consumers of my library can have types.

My work in progress so far looks like this script, but I'm having trouble importing it in my repo.

Am I on the right path? Does my root file need to be wrapped in a declaration?

#
# Helper script to generate a master Typescript definition file.
#
INPUT_FILES=src/components/*/index.js
OUTPUT_FILE=types/index.d.ts
regex='src/components/([A-Za-z]+)/index.js'

# Initialize the output file with a header
cat > $OUTPUT_FILE <<- EOM
// Type definitions for <my project>
// Project: <my project>
// Definitions by:

/// <reference types="my-project" />

EOM

# Loop through all input files and run react2dts on them,
# concatenating the output to our single output file
for file in $INPUT_FILES; do
  [[ $file =~ $regex ]]
  comp_name=${BASH_REMATCH[1]}
  $(npm bin)/react2dts --file "$file" --name $comp_name >> $OUTPUT_FILE
done

Support for commonjs output

First off, thanks for the awesome module. The output looks great.

Currently, I am trying to compile flow definitions from the definitions created by this module, however that library doesn't understand es6 modules (https://github.com/joarwilk/flowgen). Would love for this library to be able to support commonjs output, otherwise, we will have to run babel on the output to transpile it.

Just the first export is processed if a file contains multiple exports

I'm trying to process a file that looks like this:

export { ApplyTheme } from './ApplyTheme'
export { ThemeablePropValues } from './ThemeablePropValues'
export { applyCustomMediaToCss } from './applyCustomMediaToCss'
export { applyVariablesToNode } from './applyVariablesToNode'
export { formatVariableName } from './formatVariableName'
export { formatVariableNames } from './formatVariableNames'
export { getCssText } from './getCssText'

the program seems to process just the first definition, this is the output:

import * as React from 'react';

export interface ApplyThemeProps {
    /**
     * set theme variables to override the defaults
     */
    theme?: Object;
    /**
     * accepts only one child (children must be wrapped in a single component/element)
     */
    children?: React.ReactNode;
    /**
     * Prevent overriding this theme via a child ApplyTheme component or theme props
     */
    immutable?: boolean;
}

export class ApplyTheme extends React.Component<ApplyThemeProps, any> {
    render(): JSX.Element;
}

This is how I'm calling the script:

const babelPlugins = ['optionalChaining', 'nullishCoalescingOperator']
return react2dts.generateFromFile(null, filePath, {
        babylonPlugins: babelPlugins
      })

Am I doing something wrong? Or this functionality is not supported?

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.