DEV Community

Bruce Axtens
Bruce Axtens

Posted on

Typescript and external libraries

Today I learned how to make external libraries "visible" to Typescript. I asked the question on StackOverflow as How to define items to be ignored in Typescript which you can read now or later.

As you may recall, I started using Typescript yesterday. It's made a big difference already to the quality of my code so I thought I'd use it on other things, like Lychen and related in-house projects that use ClearScript to add JavaScript as an extension language.

The difficulty I was having in VSCode was how to make the various C# objects that I had exposed to JavaScript comprehensible to Typescript so that I wasn't being constantly flagged with things that weren't actually errors.

The example I gave on StackOverflow was of an object that talks to a proxy provider.

  that.getMyIP = function () {
    var request = new CSRestRequest();
    request.AddParameter("user", username);
    request.AddParameter("pass", password);
    request.AddParameter("command", "getmyip");
    var response = client.Execute(request);
    return response.Content.trim();
  };
Enter fullscreen mode Exit fullscreen mode

CSRestRequest is a symbol injected into the JavaScript interpreter from the C# side. It's a wrapping of a RestSharp object. Typescript was flagging CSRestRequest and the AddParameter methods as 'problems'.

Kudos to SciFiThief who pointed me at the documentation and gave a brief example. Subsequent contributors added more detail.

Now I have a file in my ts folder called external.d.ts which contains

declare class CSRestRequest {
    constructor (str?:any) ;
    AddParameter(a:string, b:string) : any;
}

declare class CSRestClient {
    constructor(str?:string);
    Execute:(client:any);
}
Enter fullscreen mode Exit fullscreen mode

And now my editing experience is improved and I can focus on the the code at hand and not be distracted by the wiggly red lines of false-positives under my code.

Top comments (2)

Collapse
 
somedood profile image
Basti Ortiz

Oh, dang. I never knew that. Thanks!

Are there any other special declaration file names we should be aware of? As of now, I only know about lib.d.ts and external.d.ts.

Collapse
 
bugmagnet profile image
Bruce Axtens

According to the templates page there are seven, and that's not counting lib and external.

There's a blurb about them on StackOverflow