Let’s add jQuery to our project to see how we can use type definitions.

I. Add jQuery to HTML

We will use jQuery CDN to

Add this line to index.html just before link to index.js:

from index.html:

...
<script
  src="http://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script>
...

II. Refactor code

Let’s refactor our code to use jQuery:

index.ts:

class Task {
    private priority: number;
    private title: string;
    constructor(priority: number, title: string) {
        this.priority = priority;
        this.title = title;
    }
    toString(): string {
        return `Priority: ${this.priority}, Title: ${this.title}`;         
    }
}

class HighPriorityTask extends Task {
    toString(): string {
        return `<strong>${super.toString()}</strong>`
    }
}

class TaskFactory {
    static getTask(priority: number, title: string): Task {
        if (priority === 1) {
            return new HighPriorityTask(priority, title);
        } else {
            return new Task(priority, title);
        }
    } 
}

let tasks: Task[] = [];
$('#btn-add').click(function(e) {
    e.preventDefault();
    const task = TaskFactory.getTask(Number($('#task-priority').val()), 
                          String($('#task-title').val()));
    tasks.push(task);
    let domString = '';
    tasks.forEach(t => {
        domString += `<li>${t.toString()}</li>`;
    });
    $('#task-list').html(domString);
});

But when we try to compile it we see an error:

index.ts(30,1): error TS2304: Cannot find name '$'.
index.ts(32,38): error TS2304: Cannot find name '$'.
index.ts(32,65): error TS2304: Cannot find name '$'.
index.ts(38,5): error TS2304: Cannot find name '$'.

Our compiler knows nothing about $ variable that jQuery uses to identify itself and we need to provide it.

III. Create package.json

We need to create package.json:

in console:

npm init -y

IV. Install jQuery typings and add reference

Next step - install type definition file for jQuery:

in console:

npm i @types/jquery

TypeScript automatically picks type definition and understands $ variable name. But we have other error now:

node_modules/@types/jquery/index.d.ts(41,63): error TS2304: Cannot find name 'Iterable'.

The error tells us that TypeScript doesn’t understand what is Iterable.

We need to modify tsconfig.json and add lib section:

{
    "compilerOptions": {
        "sourceMap": true,
        "watch": true,
        "noEmitOnError": true,
        "lib": ["es2015", "dom"]
    },

    "files": [
        "index.ts"
    ]
}

Now the error has gone.

See source code for this step on GitHub