Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import Javascript file into Typescript

I was wondering how I start the Twitter-Bootstrap from Typescript.

$('.carousel').carousel()

I had to implement jquery.d.ts to fix the $-sign call, but then I'm still getting the error that .carousel() could not be found in jquery.d.ts.

I tried to do this with bundling the javascript to a module and call it like that. But it does not seem to work. This is my code:

carousel.d.ts

declare module 'carousel/carousel' {
    var start: any; 
    export = start;
}

carousel.js

System.register('carousel/carousel', [], true, function () {
    var carousel = function () {
        function carousel() {
        }
        carousel.prototype.start = function () {
            $('.carousel').carousel();
        }
    }
    exports.carousel = carousel;
});

app.ts

import {Component} from "angular2/core";
import {bootstrap} from 'angular2/platform/browser';
import {Carousel} from "carousel/carousel";

@Component({
    selector: "carousel",
    bindings: [CarouselComponent],
    templateUrl: 'carousel.html'
})

export class CarouselComponent {
    start() {
            carousel.start();
        }        
    }
}

bootstrap(CarouselComponent)

Thanks for helping out.

like image 921
Jeffrey Rosselle Avatar asked Feb 02 '16 08:02

Jeffrey Rosselle


People also ask

Can you add JavaScript to TypeScript?

You can use thousands of existing JavaScript libraries in your TypeScript project. Type definition files allow you to enjoy the type-checking and autocomplete features in libraries that were written in JavaScript. These files make you more productive in writing code.

How do I import files into TypeScript?

To import a class from another file in TypeScript: Export the class from file A , e.g. export class Employee {} . Import the class in file B as import { Employee } from './another-file' . Use the class in file B .


1 Answers

The problem is that you don't have the typing definition for carousel(). Like you mentioned - it's a function in Twitter-Bootstrap, but you only included the typing definitions (*.d.ts) for jQuery. You need to include them for Bootstrap the same way.

You can get the full Bootstrap tying definitions from the DefinitelyTyped project, either from their GitHub or as a NuGet package. Here are the essential parts:

interface CarouselOptions {
    interval?: number;
    pause?: string;
    wrap?: boolean;
    keybord?: boolean;
}

interface JQuery {
    carousel(options?: CarouselOptions): JQuery;
    carousel(command: string): JQuery;
}
like image 98
Gediminas Masaitis Avatar answered Oct 20 '22 00:10

Gediminas Masaitis