Code Monkey home page Code Monkey logo

scala-js-ts-importer's Introduction

Importer from TypeScript type definitions to Scala.js

This tool reads type definitions files written for TypeScript (.d.ts files) and rewrites them to .scala files usable with Scala.js.

The process is not 100 % accurate, so manual editing is often needed afterwards. This can be improved, but not to perfection, because the features offered by the type systems of TypeScript and Scala.js differ in some subtle ways.

Usage

$ sbt 'run somelib.d.ts SomeLib.scala'

License

The TypeScript Importer for Scala.js is distributed under the Scala License.

scala-js-ts-importer's People

Contributors

andrelfpinto avatar benhutchison avatar bleis-tift avatar bpholt avatar jonas avatar kyo-ago avatar mzp avatar sbrunk avatar sjrd avatar spaced 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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

scala-js-ts-importer's Issues

can't make it work

I want to import typescript definition of the jsbn lib.
I downloaded the project (downloading the zip) and did:

sbt run jsbn.d.ts BigInteger.scala math

The 'jsbn.d.ts' file is at the project root.
It compiles without problem, but then I have an error :

[info] Running org.scalajs.tools.tsimporter.Main
Usage: scalajs-ts-importer <input.d.ts> <output.scala> []
<input.d.ts> TypeScript type definition file to read
<output.scala> Output Scala.js file
Package name for the output (defaults to "importedjs")
java.lang.RuntimeException: Nonzero exit code: 1
at scala.sys.package$.error(package.scala:27)
[trace] Stack trace suppressed: run last compile:run for the full output.
error Nonzero exit code: 1
[error] Total time: 0 s, completed 17 févr. 2015 10:56:34

I don't have any idea of where the problem comes from. Actually doing a 'sbt run' without argument gives the same error.
Am I missing something?

Support missing for unions, intersections, and numeric enum entries

I'm using this thread to record translation issues that have arisen since the introduction of Typescript 2(.1)'s changes, and can provide unit tests if requested.

Example of intersection and union usages:

funcUnI<T>(objects: T[] | B[], opts?: C & {
    d?: object | number;
    e: number;
}): T;

Example of Enum with numeric entries:

declare var EnumWithNums: {
    0: number;
    1: number;
    4: number;
};

Add basic usage to README ?

Hi,
Could you update the readme to offer basic usage for scala-js-ts-importer (i.e. series of SBT steps and direct execution of the tool)?

After deciphering the build.sbt:Main, I attempted:

sbt run
OR
sbt run scalajs-ts-importer ./tmp/cordova.d.ts ./tmp/cordova.scala
OR
sbt compile

but no dice :-( .

Although I've been skirting around using Scala/SBT now for a year or two now (and being a Java dev), I'm more used to Gradle and Ant for builds (SBT is a new entity for me).

JFYI, I didn't find a 'scalajs-ts-importer' executable/jar anywhere in the built project :-(

Parse error with generic type parameter default values

When importing the AWS Lambda type definitions, I get a parser error on this block of source:

export type Handler<TEvent = any, TResult = any> = (event: TEvent, context: Context, callback: Callback<TResult>) => void;
Parse error at 539.28
'`>'' expected but `=' found
export type Handler<TEvent = any, TResult = any> = (event: TEvent, context: Context, callback: Callback<TResult>) => void;
                           ^

As of TypeScript 2.3 generic type parameters are allowed to have default values, so this should at least parse and discard the provided value.

nested class should have an export strategy

input:

declare module 'vscode' {
  export class Position {
    readonly line: number;
    readonly character: number;
    constructor(line: number, character: number);
  }
}

https://github.com/Microsoft/vscode/blob/e74a6601c3714f98fc63102e8304b00c983b6167/src/vs/vscode.d.ts#L243-L267

output:

@js.native
@JSGlobal("vscode.Position")
class Position protected () extends js.Object {
  def this(line: Double, character: Double) = this()
  def line: Double = js.native
  def character: Double = js.native
}

This is wrong for the vscode project since they use modules to export their code. This is how you would do it with the common js syntax:

const vscode = require("vscode");
const pos = new vscode.Position(0, 0)

expected:

@js.native
@JSImport("vscode", "Position")
class Position protected () extends js.Object {
  def this(line: Double, character: Double) = this()
  def line: Double = js.native
  def character: Double = js.native
}

since from the definition we don't know if the class is exported or available on the global scope, it would make sense to pass a flag: export = global | module to specify the export strategy.

Got compile error: multiple overloaded alternatives of method foo define default arguments

Got compile error:

multiple overloaded alternatives of method xhr (and more...) define default arguments

D3 typescript has some method like this -

xhr: {
            /**
            * Creates an asynchronous request for specified url
            *
            * @param url Url to request
            * @param callback Function to invoke when resource is loaded or the request fails
            */
            (url: string, callback?: (xhr: XMLHttpRequest) => void ): Xhr;
            /**
            * Creates an asynchronous request for specified url
            *
            * @param url Url to request
            * @param mime MIME type to request
            * @param callback Function to invoke when resource is loaded or the request fails
            */
            (url: string, mime: string, callback?: (xhr: XMLHttpRequest) => void ): Xhr;
        };

Importer transfered to this which is not compile-

def xhr(url: js.String, callback: js.Function1[XMLHttpRequest, Unit] = ???): Xhr = ???
def xhr(url: js.String, mime: js.String, callback: js.Function1[XMLHttpRequest, Unit] = ???): Xhr = ???

I don't know how to handle this in scala-js, maybe we have to split them to more than 2 methods?

TypeScript Interfaces should generate abstract trait members

export interface GPGPUProgram {
    variableNames: string[];
    outputShape: number[];
    params: Array<{}>;
    userCode: string;
    supportsBroadcasting?: boolean;
}

generates

@js.native
trait GPGPUProgram extends js.Object {
  var variableNames: js.Array[String] = js.native
  var outputShape: js.Array[Double]   = js.native
  var params: js.Array[js.Any]        = js.native
  var userCode: String                = js.native
  var supportsBroadcasting: Boolean   = js.native
}

which should be

@js.native
trait GPGPUProgram extends js.Object {
  var variableNames: js.Array[String]
  var outputShape: js.Array[Double]
  var params: js.Array[js.Any]
  var userCode: String
  var supportsBroadcasting: Boolean
}

At least when the declaration files are generated from TypeScript code, they can't have an implementation (no concrete definitions allowed in TS interfaces).

If they are left concrete, I they can't be overriden in subclasses:
variable outputShape cannot override a mutable variable

I'm not sure about cases in which the TypeScript declaration files only serve as type information for existing JavaScript libraries though.

protected() modifier

Sometimes after importing I get classes like

class VertexNormalsHelper protected () extends Line
I do not understand what "protected()" means here, maybe it is better to avoid it?

Cannot import MutationSummary

I am working on html bindings to scala.reactjs variables. There I need to deliver dom changes to scalajs reactive variables, for this purpose HTML5 provides Mutation observers that effectively monitor changes. I did not find them in scalajs.dom so I took a typescript library that specialize on watching DOM changes called https://code.google.com/p/mutation-summary/ and tried to use https://github.com/sjrd/scala-js-ts-importer but I got the following error there "``interface'' expected but`if' found if (typeof WebKitMutationObserver !== 'undefined')"

transfering comments

I'm using scala-js-ts-importer as a key step in generating a facade.
It works very well, thanks for doing this.

However, in my .d.ts file I have put a lot of comments between "/** ... */"
but I cannot generate those comments in the scala code.

It would be good if comments in .d.ts could be "copied/transfered" across to the scala code.

Default values

When I import ts files I often get methods like def this(object: Object3D, size: Double = ???, hex: Double = ???, linewidth: Double = ???) = this()
with a lot of default arguments and corresponding " multiple overloaded alternatives of method "
Maybe for such kind of methods it would be better to generate several methods without defaults, like
def this(object: Object3D) = this()
def this(object: Object3D, size: Double) = this()
def this(object: Object3D, size: Double, hex: Double) = this()
def this(object: Object3D, size: Double, hex: Double, linewidth: Double) = this()

I understand it is verbose but it allows to avoid doing many manual corrections.

Multiple parse errors caused in import and export syntax

When trying to convert typings for libraries like Vue or Vuetify, issues like the following seems to arise:

Vue, converting this file

amar@tekpro ~/repos/ext/scala-js-ts-importer master $ sbt 'run node_modules/vue/types/index.d.ts Vue.scala vue'
[info] Loading settings from idea.sbt ...
[info] Loading global plugins from /Users/amar/.sbt/1.0/plugins
[info] Loading settings from plugins.sbt ...
[info] Loading project definition from /Users/amar/repos/ext/scala-js-ts-importer/project
[info] Loading settings from build.sbt ...
[info] Set current project to scala-js-ts-importer (in build file:/Users/amar/repos/ext/scala-js-ts-importer/)
[info] Running org.scalajs.tools.tsimporter.Main node_modules/vue/types/index.d.ts Vue.scala vue
Parse error at 3.8
'identifier as' expected but `default' found
export default Vue;
       ^

Exception: sbt.TrapExitSecurityException thrown from the UncaughtExceptionHandler in thread "run-main-0"
[error] java.lang.RuntimeException: Nonzero exit code: 2
[error] 	at sbt.Run$.executeTrapExit(Run.scala:124)
[error] 	at sbt.Run.run(Run.scala:77)
[error] 	at sbt.Defaults$.$anonfun$bgRunTask$5(Defaults.scala:1168)
[error] 	at sbt.Defaults$.$anonfun$bgRunTask$5$adapted(Defaults.scala:1163)
[error] 	at sbt.internal.BackgroundThreadPool.$anonfun$run$1(DefaultBackgroundJobService.scala:366)
[error] 	at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:12)
[error] 	at scala.util.Try$.apply(Try.scala:209)
[error] 	at sbt.internal.BackgroundThreadPool$BackgroundRunnable.run(DefaultBackgroundJobService.scala:289)
[error] 	at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1135)
[error] 	at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
[error] 	at java.base/java.lang.Thread.run(Thread.java:844)
[error] (Compile / run) Nonzero exit code: 2
[error] Total time: 2 s, completed May 4, 2018, 9:25:52 AM

It looks like export default syntax isn't supported in the parser.

Also Vue, trying this file instead

amar@tekpro ~/repos/ext/scala-js-ts-importer master $ sbt 'run node_modules/vue/types/vue.d.ts Vue.scala vue'
[info] Loading settings from idea.sbt ...
[info] Loading global plugins from /Users/amar/.sbt/1.0/plugins
[info] Loading settings from plugins.sbt ...
[info] Loading project definition from /Users/amar/repos/ext/scala-js-ts-importer/project
[info] Loading settings from build.sbt ...
[info] Set current project to scala-js-ts-importer (in build file:/Users/amar/repos/ext/scala-js-ts-importer/)
[info] Running org.scalajs.tools.tsimporter.Main node_modules/vue/types/vue.d.ts Vue.scala vue
Parse error at 14.1
IdentifierName expected
} from "./options";
^

Exception: sbt.TrapExitSecurityException thrown from the UncaughtExceptionHandler in thread "run-main-0"
[error] java.lang.RuntimeException: Nonzero exit code: 2
[error] 	at sbt.Run$.executeTrapExit(Run.scala:124)
[error] 	at sbt.Run.run(Run.scala:77)
[error] 	at sbt.Defaults$.$anonfun$bgRunTask$5(Defaults.scala:1168)
[error] 	at sbt.Defaults$.$anonfun$bgRunTask$5$adapted(Defaults.scala:1163)
[error] 	at sbt.internal.BackgroundThreadPool.$anonfun$run$1(DefaultBackgroundJobService.scala:366)
[error] 	at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:12)
[error] 	at scala.util.Try$.apply(Try.scala:209)
[error] 	at sbt.internal.BackgroundThreadPool$BackgroundRunnable.run(DefaultBackgroundJobService.scala:289)
[error] 	at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1135)
[error] 	at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
[error] 	at java.base/java.lang.Thread.run(Thread.java:844)
[error] (Compile / run) Nonzero exit code: 2
[error] Total time: 2 s, completed May 4, 2018, 9:18:05 AM

In this case it looks like the use of trailing commas in the import list isn't being handled.

Vuetify:

amar@tekpro ~/repos/ext/scala-js-ts-importer master $ sbt 'run node_modules/vuetify/index.d.ts Vuetify.scala vuetify'
[info] Loading settings from idea.sbt ...
[info] Loading global plugins from /Users/amar/.sbt/1.0/plugins
[info] Loading settings from plugins.sbt ...
[info] Loading project definition from /Users/amar/repos/ext/scala-js-ts-importer/project
[info] Loading settings from build.sbt ...
[info] Set current project to scala-js-ts-importer (in build file:/Users/amar/repos/ext/scala-js-ts-importer/)
[info] Running org.scalajs.tools.tsimporter.Main node_modules/vuetify/index.d.ts Vuetify.scala vuetify
Parse error at 2.1
'`;'' expected but `import' found
import 'vuetify/src/util/colors'
^

Exception: sbt.TrapExitSecurityException thrown from the UncaughtExceptionHandler in thread "run-main-0"
[error] java.lang.RuntimeException: Nonzero exit code: 2
[error] 	at sbt.Run$.executeTrapExit(Run.scala:124)
[error] 	at sbt.Run.run(Run.scala:77)
[error] 	at sbt.Defaults$.$anonfun$bgRunTask$5(Defaults.scala:1168)
[error] 	at sbt.Defaults$.$anonfun$bgRunTask$5$adapted(Defaults.scala:1163)
[error] 	at sbt.internal.BackgroundThreadPool.$anonfun$run$1(DefaultBackgroundJobService.scala:366)
[error] 	at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:12)
[error] 	at scala.util.Try$.apply(Try.scala:209)
[error] 	at sbt.internal.BackgroundThreadPool$BackgroundRunnable.run(DefaultBackgroundJobService.scala:289)
[error] 	at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1135)
[error] 	at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
[error] 	at java.base/java.lang.Thread.run(Thread.java:844)
[error] (Compile / run) Nonzero exit code: 2
[error] Total time: 2 s, completed May 4, 2018, 9:17:43 AM

This case is complaining about the lack of semicolons after imports - inserting those redundant semicolons however, results in another form of import syntax failing:

amar@tekpro ~/repos/ext/scala-js-ts-importer master $ sbt 'run node_modules/vuetify/index.d.ts Vuetify.scala vuetify'
[info] Loading settings from idea.sbt ...
[info] Loading global plugins from /Users/amar/.sbt/1.0/plugins
[info] Loading settings from plugins.sbt ...
[info] Loading project definition from /Users/amar/repos/ext/scala-js-ts-importer/project
[info] Loading settings from build.sbt ...
[info] Set current project to scala-js-ts-importer (in build file:/Users/amar/repos/ext/scala-js-ts-importer/)
[info] Running org.scalajs.tools.tsimporter.Main node_modules/vuetify/index.d.ts Vuetify.scala vuetify
Parse error at 3.11
'identifier from' expected but `,' found
import Vue, { PluginFunction } from 'vue';
          ^

Exception: sbt.TrapExitSecurityException thrown from the UncaughtExceptionHandler in thread "run-main-0"
[error] java.lang.RuntimeException: Nonzero exit code: 2
[error] 	at sbt.Run$.executeTrapExit(Run.scala:124)
[error] 	at sbt.Run.run(Run.scala:77)
[error] 	at sbt.Defaults$.$anonfun$bgRunTask$5(Defaults.scala:1168)
[error] 	at sbt.Defaults$.$anonfun$bgRunTask$5$adapted(Defaults.scala:1163)
[error] 	at sbt.internal.BackgroundThreadPool.$anonfun$run$1(DefaultBackgroundJobService.scala:366)
[error] 	at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:12)
[error] 	at scala.util.Try$.apply(Try.scala:209)
[error] 	at sbt.internal.BackgroundThreadPool$BackgroundRunnable.run(DefaultBackgroundJobService.scala:289)
[error] 	at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1135)
[error] 	at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
[error] 	at java.base/java.lang.Thread.run(Thread.java:844)
[error] (Compile / run) Nonzero exit code: 2
[error] Total time: 1 s, completed May 4, 2018, 9:22:04 AM

The implementation of import syntax seems to be fairly distant from the possibilities in current versions of TypeScript.

I'm happy to update the parser to support more of these cases - that said however, I'm hesitant to make updates if it might prove to be a recurring theme elsewhere that TypeScript syntax isn't fully captured.

Any thoughts on how this could proceed?


Aside:

Given that dependencies only point to scala-parser-combinators and scalatest, might a more maintainable option be to look into targeting Scala.js and using TypeScript's own compiler interface for parsing instead (similarly to e.g. https://github.com/rrdelaney/ReasonablyTyped)? A stretch would be scalameta output, too. This might be more in the scope of a wholly new project, however.

Support for object type literal

In case of

[info] Running org.scalajs.tools.tsimporter.Main d3.d.ts d3.scala
Parse error at 1642.48
identifier expected
        export function ordinal<Domain extends { toString(): string }, Range>(): Ordinal<Domain, Range>;

parse default type parameters "type Foo<P = any>"

It's probably safe to ignore them, but I received parse errors on:

type ReactType<P = any> = string | ComponentType<P>;

Error:

Parse error at 74.22
'`>'' expected but `=' found
    type ReactType<P = any> = string | ComponentType<P>;

overrides

The most common error that I get after porting ts file is "method needs override modifier". It would be great if importer looked at class hierarchy and put overrides instead of me.

number[]|string[] type disjunction fails

Hi, I'm trying to convert https://github.com/photonstorm/phaser/blob/master/typescript/phaser.d.ts to scalajs but fails in the line 58

``)'' expected but ErrorToken(illegal character) found
        constructor(game: Phaser.Game, parent: Phaser.Sprite, name: string, frameData: Phaser.FrameData, frames: number[]|string[], frameRate?: number, loop?: boolean);

the reason is pretty clear, scalajs doesnt support this type number[]|string[] ..not pretty sure but I think than it's named type disjunction no? :) .

how can handle it in scalajs?..thanks!!

Translate Typescript typenames to Scalajs names

When working with the Typescript to Scalajs Importer, Im noticing that it references TS types such as ReadonlyArray, Uint32Array and PromiseLike, but they aren't defined in Scalajs under those names.

  • PromiseLike[A] is called js.Thenable[A] in Scala.js. This name aligns with the ECMAScript specification.
  • ReadonlyArray[A] is represented as js.Array[_ <: A] in Scala.js.
  • Uint32Array is js.typedarray.Uint32Array

This issue tracks feature to translate such TS names to Scalajs names so that the emitted Scala code compiles correctly. Predecessor scala-js/scala-js#3498

Parse error on private field with type

When importing type definitions for Pixi.js, I got a parse error on the code like below

export class Application {
    constructor(options?: ApplicationOptions);
    constructor(width?: number, height?: number, options?: ApplicationOptions,
         noWebGL?: boolean, sharedTicker?: boolean, sharedLoader?: boolean);

    private _ticker: ticker.Ticker;

    ...
}
Parse error at 6.24
'`}'' expected but `:' found
        private _ticker: ticker.Ticker;
                       ^

It is a bit strange for me that TypeScript allows private members in type definitions, since those are invisible for library users.

Anyway, It would be helpful to support parse privater members with type, since they are widely used in type definitions.

$ git clone https://github.com/DefinitelyTyped/DefinitelyTyped
$ cd https://github.com/DefinitelyTyped/DefinitelyTyped
$ git grep -E "private \w+: \w+" | wc -l
261

Since they are private, I think importer should ignore private members, in other words, print nothing.

Feature: Optional field foo? should be translated to js.UndefOr

TypeScript has foo? notation to indicate optional (can be null/undefined) type

Currently, scalajs-ts-importer converts foo?: T; into foo: T which can not accept js.undefined.


var state: Int = js.native

I think it should be converted to js.UndefOr[T]

Union type not accepted as upper bound of a generic type parameter

I am having problems with union types.

Running:

sbt 'run simple.ts Simple.scala'

With a file simple.ts:

interface A {}
interface B {}

function f<T extends A | B>(t: T) {
}

I get:

Parse error at 4.24
'`>'' expected but `|' found
function f<T extends A | B>(t: T) {
                       ^

Can we handle overload methods?

All overloaded methods become var.
A piece of d3 typescript from https://github.com/borisyankov/DefinitelyTyped -

export interface Selectors {
        /**
        * Select an element from the current document
        */
        select: {
            /**
            * Selects the first element that matches the specified selector string
            *
            * @param selector Selection String to match
            */
            (selector: string): Selection;
            /**
            * Selects the specified node
            *
            * @param element Node element to select
            */
            (element: EventTarget): Selection;
        };

        /**
        * Select multiple elements from the current document
        */
        selectAll: {
            /**
            * Selects all elements that match the specified selector
            *
            * @param selector Selection String to match
            */
            (selector: string): Selection;
            /**
            * Selects the specified array of elements
            *
            * @param elements Array of node elements to select
            */
            (elements: EventTarget[]): Selection;
        };
    }

is imported as -

@JSName("D3.Selectors")
trait Selectors extends js.Object {
  var select: js.Any = ???
  var selectAll: js.Any = ???
}

Parse error in union types with leading |

When importing the AWS Lambda type definitions, I get a parser error on this block of source:

export interface CognitoUserPoolTriggerEvent {
    version: number;
    triggerSource:
        | "PreSignUp_SignUp"
        | "PostConfirmation_ConfirmSignUp"

(The whole file is here.)

Parse error at 208.9
'`('' expected but `|' found
        | "PreSignUp_SignUp"
        ^

I'm having trouble pointing to exactly what in the TypeScript grammar allows this syntax, but the example below seems to work in the TypeScript playground so I'm assuming it's valid.

type NumberOrString = | number | string;

ParseError on trailing comma in parameter list

    signupAndLogin(
        options: {
            /** user email address */
            email: string,
            /** user password */
            password: string,
            /** name of the connection where the user will be created */
            connection: string,
        },
        callback: Auth0Callback<any>,
    ): void;

This currently causes a

Parse error at 312.5
IdentifierName expected
    ): void;

Due to the trailing comma after callback

error with import inside declared module

Hi..sorry but I'm trying convert the atom.d.ts from definitelytyped

when I run the importer I get an error in the line 1263:

  Parse error at 1263.2
  ``}'' expected but `import' found
     import spacePen = require("space-pen");

      ^

seems than to the importer doesnt like that import clause inside a module declaration...this is the code

  declare var atom:AtomCore.IAtom;

  declare module "atom" {
     import spacePen = require("space-pen"); // <----here is the problem!!

     var $:typeof spacePen.$; 

I'm not so much familiar with typescript and I don't know how fix it by hand..can you give me a clue??..thanks

parse "export as namespace"

Given:

export as namespace ReactDOM;

the parse error is:

Parse error at 11.8
'`='' expected but identifier as found
export as namespace ReactDOM;

Inconsistent Discard of Specialized Signatures

There is logic in Importer.scala#L228-L230 to discard specialized signatures (i.e. literal types encoded as ConstantType), but it is applied inconsistently.

// Discard specialized signatures
if (signature.params.exists(_.tpe.exists(_.isInstanceOf[ConstantType])))
return

So, a function defined as

update(input: 0): void;

will be discarded, whereas function with a union type containing a ConstantType in one of its cases will not be discarded:

update(input: 0 | 1): void;

results in

def update(input: Int): Unit = js.native

I'm not sure what motivates the original discard. Is it because the Scala Int type isn't an actual match for the TrueScript 0 | 1? (If so, the discard logic should probably look deeper at UnionType instances.) If not, can someone elaborate as to why the function is discarded?

FWIW, there is a "workaround;" the function will be included in the Scala trait by defining in TypeScript

update(input: 0 | 0): void;

but that seems like quite a hack to me.

Support `export const enum`

export const enum doesn't seem to be handled.

Example

Parse error at 3069.23
'`}'' expected but identifier RenderLineNumbersType found
    export const enum RenderLineNumbersType {
                      ^

Support for typescript Type Guards

I tried running on Monaco Editor and discovered the importer doesn't handle TS Type Guards.

Example

Parse error at 81.48
'`:'' expected but identifier PromiseLike found
        public static is(value: any): value is PromiseLike<any>;

overrides for var

Sometimes the importer generates code like
override var image: js.Any = ???
But it is not possible to override var-s in Scala

Importing angular.d.ts

Hi,

While trying to import the angular-1.2.d.ts (same for 1.3) from DefinitelyTyped repository, scala-js-ts-importer (master) hit the following error:

[info] Running org.scalajs.tools.tsimporter.Main angularjs/angular.d.ts angularjs/angular-1.0.d.ts.scala
Parse error at 350.62
``)'' expected but `[' found
        $watchGroup(watchExpressions: {(scope: IScope) : any}[], listener: (newValue: any, oldValue: any, scope: IScope) => any): Function;

                                                             ^

In case we simply comment this line, we then encounter another one 5 lines after:

[info] Running org.scalajs.tools.tsimporter.Main angularjs/angular.d.ts angularjs/angular-1.0.d.ts.scala
Parse error at 355.9
``}'' expected but `this' found
        this: IRootScopeService;

        ^

Then, if commented, another one appear later:

[info] Running org.scalajs.tools.tsimporter.Main angularjs/angular.d.ts angularjs/angular-1.0.d.ts.scala
Parse error at 600.67
identifier expected
        all(promises: { [id: string]: IPromise<any>; }): IPromise<{ [id: string]: any }>;

                                                                  ^

Again after having commented the previous one:

[info] Running org.scalajs.tools.tsimporter.Main angularjs/angular.d.ts angularjs/angular-1.0.d.ts.scala
Parse error at 639.9
``}'' expected but `catch' found
        catch<TResult>(onRejected: (reason: any) => IHttpPromise<TResult>): IPromise<TResult>;

        ^

Then, the last one:

[info] Running org.scalajs.tools.tsimporter.Main angularjs/angular.d.ts angularjs/angular-1.0.d.ts.scala
Parse error at 643.9
``}'' expected but `finally' found
        finally<TResult>(finallyCallback: ()=>any):IPromise<TResult>;

        ^

Source files:
1.3: https://github.com/borisyankov/DefinitelyTyped/blob/master/angularjs/angular.d.ts
1.2: https://github.com/borisyankov/DefinitelyTyped/blob/master/angularjs/legacy/angular-1.2.d.ts

Would you have an idea on how to solve this?

Thanks!

Jean Luc

Support for string enums

I'm trying to convert a Typescript file with the following enum definition:

export enum Type {
  Submit = "submit",
  Reset = "reset",
  Button = "button"
}

.. and it fails with the following parsing error:

[info] Running org.scalajs.tools.tsimporter.Main Button.tsx Button.scala
Parse error at 9.12
number expected
  Submit = "submit",

Looking at the Typescript docs this should be a valid string enum: https://www.typescriptlang.org/docs/handbook/enums.html#string-enums

It would be a great to see this feature added to the scala-js-ts-importer.

Enum values are not parsed correctly

Enum members can have optional values. At the moment they are parsed by parsing a number or a string.
The specification, however, allows full expressions, like

enum Test {
  Member = (1 <<  2)
}

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.