3

I noticed that using /// <reference path="*.js"> doesn't work. I don't understand why.

Just a clarification: I KNOW about d.ts files, and I know what value is added by creating them to decorate a js file - they allow me to enjoy type-safety even when using an external library which wasn't written in typescript.

What I don't understand is why I still have to write a d.ts file even if I'm willing to forgoe type-safety.

Let's assume, for example, that I have a big JS file I have written, which contains many function definitions. These functions have names and lists of parameters. Can't the TS compiler automatically 'declare' those functions for usage? It would be a temporary solution, but it would facilitate migrating to TypeScript so much!

Is there a reason I'm missing that this is not possible, or is it just an unimplemented feature?

1 Answer 1

8

Passing a JavaScript file as a reference path won't work because references are solely used to build upon the type information for your program and a JavaScript file cannot supply this type information (although if you drop your JavaScript code into a .ts file, you'll find out how far away you are from inferring the types).

You don't have to write a .d.ts file if you don't want type checking... you just tell the compiler that you don't want type checking. For example, if you wanted to use jQuery without any type checking...

declare var $: any;

$("anything").whateverIsTypedWillBeAllowed("like this");

The first line says "I'm going to be using a var named $ and I don't care about type safety when I use it".

Sign up to request clarification or add additional context in comments.

4 Comments

While the jQuery.js file doesn't have any type information, it does have function and 'class' definitions - why can't TS use that? Not as good as a full d.ts file, but better than no type checking at all
You can paste the whole of jQuery into a TypeScript file if you want to see how much can be inferred - this will give you an idea of the scale of things. Once you have written a few definition files, you realise how much is missing from plain JS.
I suppose, but wouldn't it be categorized under "better than nothing"?
Try it out - if you can get your JavaScript to at least compile in a TypeScript file you can switch on 'generate type definitions' on the TypeScript compiler and you get a free .d.ts file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.