Reference javascript file inside typescript - javascript

I would like to use a javascript function inside a typescript file. How can I reference the javascript file containing that function inside typescript file?
I tried
<reference path="../libs/myjsfile.js" />
this brings an error while building like: Cannot resolve referenced file: ../libs/myjsfile.js

While the two answers above will work for a small or single variable API, the correct answer is to write a type declaration file for your JavaScript file.
The type declaration file for your example would be named myjsfile.d.ts, where the .d.ts suffix is what tells the TypeScript compiler that it's parsing a declaration file. If you use Visual Studio, your declaration file will be recognized by the TypeScript compiler as long as it is somewhere (anywhere) in the project you are working on.
Declaration files store metadata about JavaScript variables, functions and objects so the TypeScript compiler can do its job. If your JavaScript file happens to be a library or framework in common use, DefinitelyTyped is definitely the place to find the definition file you need.
If your JavaScript is your own work or less well known, you'll have to write your own type declaration file. See the section Writing .d.ts files in The TypeScript Handbook.
If the name declaration file sounds intimidating, don't worry - they are far easier to write than programs. Also, remember that you don't need to specify all metadata for your JavaScript file, just the functionality you need.
Let me know if you need any help!

You just have to tell the compiler that the method exists outside typescript:
declare function myJavaScriptFunction(param1: number, param2: JQuery): void;
Be sure that the website loads all files needed, the normal js files and the js files that the typescript compiler generated

You can see the latest version of the TypeScript documenttion in TypeScript
Handbook on GitHub:
Working with Other JavaScript Libraries
Writing Definition Files
Also I am recomending you the tsd utility to search and install TypeScript definition files directly from the community driven DefinitelyTyped repository. This repository contains definition files *.d.ts for the most popular javascript libraries.

this brings an error while building like: Cannot resolve referenced file: ../libs/myjsfile.js
Reference file tags are for TypeScript not JavaScript. You would load JavaScript using a script tag in your page (or something like requirejs).
To use the JavaScript from TypeScript you would declare the API of the javascript you want to use for TypeScript consumption (as AKR pointed out).

Related

Vscode available properties intellisense using javascript or typescript in a function which's parameter is a string

Look here.
For the first parameter of the addEventListener function, vscode gives me several inbuilt suggestions
How should I make this available in my javascript function?
It could be using Jsdoc or typescript etc.
You can always see what vscode uses for intellisense by hovering on the addEventListener method or ctrl + click to go to the definition in lib.dom.d.ts file where all definitions are present.
By doing the above you will see that the vscode uses the keys of a class called WindowEventMap.
So your function accepting a event listener name could be
function myFunc(event: keyof WindowEventMap): void {
}
A .d.ts file contains typings for java script code. This is how you get typings like the one in your question and from some packages published to npm.
How is your javascript function used by others?
Are you creating a javascript library which will be used by others? Then either use typescript during development and let typescript generate .d.ts files for your code for you. Or If you are not using typescript for development you will have to create your own declarations. And publish your library with these .d.ts file(s). Refer to DefenitelyTyped project for examples.
A file in the same project which uses this function? If you are using typescript like i mentioned in the code snippet above, then intellisense will automatically be shown for users. Else if you are using javascript, then you can still try and create .d.ts files and refer to them in your ts config (Haven't tried this myself).

Kotlin JavaScript to TypeScript Definition File

I have found the ts2kt library which will create Kotlin header files from arbitrary .d.ts files. But, I want to go in the opposite direction.
I want to build a Kotlin library that will compile to JavaScript, but I want to use it from TypeScript. Is there a way to make Kotlin generate a .d.ts file(s) from its exposed interfaces? Am I approaching this the right way?
In Kotlin 1.4-M1 support for exporting TypeScript definitions was added
Preview: TypeScript definitions
Another feature in the new Kotlin/JS IR compiler we’re excited to show off is the generation of TypeScript definitions from Kotlin
code. These definitions can be used by JavaScript tools and IDEs when
working on hybrid apps to provide autocompletion, support static
analyzers, and make it easier to include Kotlin code in JS and TS
projects.
For top-level declarations marked with #JsExport (see above) in a project configured to use produceExecutable(), a .d.ts file with the
TypeScript definitions will be generated. For the snippet above, they
look like this:
// [...]
namespace blogpost {
class KotlinGreeter {
constructor(who: string)
greet(): string
}
function farewell(who: string): string
}
// [...]
In Kotlin 1.4-M1, these declarations can be found in build/js/packages/<package_name>/kotlin alongside the corresponding,
un-webpacked JavaScript code. Please note that since this is only a
preview, they are not added to the distributions folder by default for
now. You can expect this behavior to change in the future.
I'm looking to do something like this to share models between Android and JS. There is the ts-generator library, which takes jvm classes and generates ts definitions from them.
I haven't tried this yet, but it theoretically should work. Separate the API for your library (or an interface the api implements) into a kotlin common module. You can then compile the api into a jvm module, and run it through the ts-generator to generate ts definitions.
Maybe there is a clever way to do this to skip the compilation to jvm for ts definition generation.

How to write typescript definition files for new library?

If you were to write your own open source typescript library how would you structure the typescript and the typescript definitions? From what I understand the definition files are really there for the compiler so that when your library gets consumed there is intellisense to help the consumer.
However, how do definition files work internally when developing a library? Would you put all of your types (interfaces, classes, etc) in a {module}.d.ts file and reference the definition file internally so that you don't have to write the types twice (once in the {module}.ts and once in the {module}.d.ts?
In the typescript compiler options what is the point of setting "declaration" to true? To me it doesn't seem helpful to automate the definition file creation if it won't be very helpful (i.e. comments).
If your library has multiple modules would you write a separate definitions for each module and add references between definitions then concatenate them with some automater (i.e. gulp, grunt)?
What is the recommended way to expose your library so that both typescript consumers and javascript consumers can use your library?
How would you write tests in typescript? Would you import the typescript modules in your test files?
When developing your library in typescript you do not use definitions of your own classes. They are 'self contained' and already provide all type information to transpiler/IDE. The definitions are as you have mentioned for external consumers.
The point of setting declaration to true is to get rid of tedious job of collecting type information from typescript classes and pasting it in definition files. As I have said this information is already present in typescript files and can be automatically extracted by transpiler.
Regarding the way of how to organize your definitions and expose them - I am sure there are multiple different ways, one thing for sure - you do not want to write the same class definitions manually in two places. Having said that I can give you a sample of how I expose library project and consume it in another one.
Pay attention to index.ts files there and how the root one is exposed in package.json -> typings field. There you will also find exampls of unit tests for the library via jasmine.
Hope this will give you some information of how to go process with your library development.

Should TypeScript Interfaces Be Defined in *.d.ts Files

TypeScript newbie question. In our project, we are using some external JavaScript libraries where we needed to add *.d.ts files. I understand this use case and the reason why we needed to do this.
But, for our own interfaces that we are defining, one of my developers suggested that we define them in *.d.ts files so that we could have access to the interface type without importing it into the modules that need to use it.
For example, we wanted to create an interface for an "error-first callback" function so that we could reuse it in many areas.
So instead of this...
export function helloWorldEventually(callback: (err: Error, result: any) => void) {
callback(null, 'Hello World');
}
We could define an interface for the error first callback like this...
export interface ErrorFirstCallback {
(err: Error, result: any): void;
}
And use it like this...
export function helloWorldEventually(callback: ErrorFirstCallback) {
callback(null, 'Hello World');
}
At first, I just defined the ErrorFirstCallback interface in ErrorFirstCallback.ts, and imported it in order to reference it.
Another developer suggested we put in in a *.d.ts file and then we would not need to import it in order to reference it.
When should interfaces that we are defining be defined in a *.d.ts file vs a *.ts file.
Thanks!
Declaration files describe the shape of external JavaScript libraries. For example using jQuery with $ will result in a TypeScript error without declaration files, because $ or JQuery is undefined. Therefor a declaration file creates an interface, so the compiler knows "if this variable is of type JQuery it must have the functions x,y,z"
When creating interfaces for your project, you should put them where ever you like: Within one big interface-file, within an individual file for each interface, or within the file where it may belong to, BUT within a declaration file would be very inconvenient.
Personally i like to have individual files for each module/class/interface. But its just a matter of taste.
The only thing considering creating a declaration file is to give other developers the possibility to use you final JavaScript file(not TypeScript!) in their project.
Another developer suggested we put [the interface] in a *.d.ts file and then we would not need to import it in order to reference it.
Using a .d.ts vs. .ts file is unrelated to providing a type declaration in a local/module or global/script scope.
You can export the interface ErrorFirstCallback, so others will have to import it. Or you don't use export/import to make the file a global script. Then, ErrorFirstCallback can be used without an import. It doesn't matter, if the file has a .ts or .d.ts extension in this case.
When should interfaces that we are defining be defined in a *.d.ts file vs a *.ts file.
What does matter is, that .d.ts files are only seen as compiler input and not emitted to your dist/build folder.
As a good rule of thumb, you put the type in a .ts, if you want to provide it as part of an npm package or public typed API to make your life easier with the build step (it will be emitted as compiler output).
You can use .d.ts files for internally used types of your project.
Are you using typings? That seems to be the community way to manage third party types. That way you don't have to manage defining other developers' APIs.
As a point of reference the Node environment d.ts appears to just define the (err, res) callbacks throughout the API (https://github.com/typed-typings/env-node/blob/master/6/node.d.ts)

JavaScript Intellisense in TypeScript File

Is it only possible to get intellisense in TypeScript files by referencing .ts files with own coded interfaces?
Is there a solution for existing JavaScript libraries?
You are able to get IntelliSense for other TypeScript files by using an external script reference directive at the top of your script:
///<reference path="someOtherScript.ts" />
As a side note, the TypeScript IntelliSense reference directive doesn't support the tilde operator like the JavaScript reference directive does. For example, if your script is located in "~/Scripts/foo/", in JavaScript you can reference:
///<reference path="~/Scripts/otherScriptFile.js" />
whereas in TypeScript you have to reference relative to the current file:
///<reference path="../otherScriptFile.ts" />
More info about this can be found in section 11.1.1 Source Files Dependencies of the TypeScript Spec.
With regard to JavaScript IntelliSense in a TypeScript file, it currently appears to be not possible to get JavaScript reference IntelliSense.
As others before me have pointed out, you need the definition files.
The DefinitelyTyped GitHub repository provides an excellent (and growing) list of definition files for a lot of popular libraries.
You'll get intellisense support for every JS code (quality may vary), however the typescript specific stuff is only available when using apropriate definition files (*.d.ts).
You can find additional definition files in the source repository (> typings, currently only jQuery and WinJS/RT) http://typescript.codeplex.com/SourceControl/BrowseLatest

Categories

Resources