-1

I am trying to create a javascript object from Typescript.

This is the Javasript object I am trying to create: https://cdnjs.cloudflare.com/ajax/libs/chess.js/0.10.2/chess.js

In the javascript sample, you just create the object like this:

this.engine = new Chess();

How do I do this in Typescript?

I imported the object like this (I downloaded the file and added it to my project):

import * as Chess from './../chess.js';

However, if I try to create a Chess object I get a build error:

const engine = new Chess();

Error says: Cannot use 'new' with an expression whose type lacks a call or construct signature.

TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94
  • 1
    At least related: https://stackoverflow.com/questions/12687779/how-do-you-produce-a-d-ts-typings-definition-file-from-an-existing-javascript – T.J. Crowder Nov 21 '17 at 18:18
  • Are you using a type definition file (.d.ts) for the referenced script ? – Sefe Nov 21 '17 at 18:19
  • 3
    *"Creating Javascript object from Typescript"* You don't have "JavaScript objects" and "TypeScript objects," you just have objects. TypeScript compiles (transpiles) to JavaScript. What you're lacking is a type definition file (`*.d.ts`) for the JavaScript library you want to use which tells TypeScript the types of the things in that library. – T.J. Crowder Nov 21 '17 at 18:19
  • 1
    Potentially related as well: https://stackoverflow.com/questions/43437964/typescript-declaration-file-for-chess-js – mhodges Nov 21 '17 at 18:20

1 Answers1

0

Thanks everyone for your responses. I did a lot of digging into the different methods and I found this just might work.

npm install --save chess.js

This creates a node module for chess.js.

From there I can create the class object like this:

import * as Chess from "./../../node_modules/chess.js";

var chess = new Chess();

I have not tested it in depth, but I was able to call functions in the class.

Paolo
  • 20,112
  • 21
  • 72
  • 113
  • Hey Michael. Figured this might be late & hoping it helps someone in the future. I wrote the typings file for chess.js but have been too lazy to add it to definitelyTyped (i swear, i will get to it someday) In the mean time, you can find it here: [Git Repo](https://github.com/Sliverb/angular-firebase-chess/tree/master/src/typings). Having this in your folder should allow typescript to properly ref the lib, meaning you can go back to using this "import * as Chess from 'chess.js';" – Bayo O Jun 06 '18 at 02:47