JavaScript reference in TypeScript file - javascript

I have a JavaScript file from:
http://javascriptsoapclient.codeplex.com/
I need to write my program in TypeScript.
My problem is now that I don't know how to integrate this .js file in my .ts file.
I want to use SOAPClient from the .js file to invoke methods from the Service.
Some code from the .js:
function SOAPClient() {}
SOAPClient.invoke = function(url, method, parameters, async, callback)
{
if(async)
SOAPClient._loadWsdl(url, method, parameters, async, callback);
else
return SOAPClient._loadWsdl(url, method, parameters, async, callback);
}
I tried it this way: /// <reference path="soapclient.js" /> but it doesn't work.
Please help me!
Thanks in advance.

You need to build a definition for the external JavaScript. The best way to start with this is to look at your usage. For example, I have taken the "Hello World" example from the documentation:
function HelloWorld() {
var url = 'http://localhost/';
var pl = new SOAPClientParameters();
SOAPClient.invoke(url, "HelloWorld", pl, true, HelloWorld_callBack);
}
function HelloWorld_callBack(r) {
alert(r);
}
In order to get auto-completion and type checking for the features used, you would need to put the following code inside a file named SoapClient.d.ts.
declare class SOAPClientParameters {
}
interface SOAPClient {
invoke(url: string, method: string, parameters: SOAPClientParameters, async: boolean, callback?: (response: any) => any);
}
declare var SOAPClient: SOAPClient;
In Visual Studio, this will give you the auto-completion and type checking. In some IDEs you need to add a reference comment to the TypeScript file that calls SOAPClient:
///<reference path="SoapClient.d.ts"/>
You still need to remember to add the actual SOAPClient JavaScript file to your page so it is available at runtime.
There are full instructions on creating your own type definitions here: Complex Type Definitions Made Easy.

declare var SOAPClient: any;
Should get you started :)

Related

When should we load the function, if we want to add a function to a prototype using React?

I am trying to add a toCamelCase function to the String prototype in React with TypeScript.
Here is what I did, in a toCamelCase.d.ts file:
interface String {
toCamelCase(): string;
}
String.prototype.toCamelCase = function (): string {
return this[0].toUpperCase() + this.slice(1).toLowerCase();
};
Now I am just wondering when and in which file should I load this script so I can get access to it.
I am aware that I can simply define a function and use that.
However, I am curious how to do it with prototype and what would be the downside doing things like this if there are any.
Where to do it?
In main.js or index.js or any other file that bootstraps your application
What are the downsides?
You can never know if one of the libraries that you use using relies on String.prototype being unaltered. It can cause major issues that you will have a hard time finding.

Is it possible to only convert a dart function to javascript

I am currently using the following package where the readme illustrates the following
final bool loaded = await JsIsolatedWorker().importScripts(['test.js']);
I am using the isolate worker package so my code can work on web and outside of web. I would like to generate javascript code from my dart code. I have one file with a top level function and I use
dart compile js -O0 -o test.js test.dart
which I found here
https://dart.dev/tools/dart2js
this is my dart file
void main(List<String> args) {
doComputation('');
}
String doComputation(String input) {
return 'output';
}
I can generate javascript only if I have a main function but this generates a javascript file where the doComutation is not a top level function, so I am not sure if the package can call the function. It looks like it generates an entire program instead of just generating one function.
The generated file is too long to post
So what my question comes down to is this. Is there a way to generate javascript from dart for 1 function with its dependencies included instead of having to generate the entire program? So that I can call this function from dart.
I am not an expert but I also had this problem. Here's what worked for me:
In web_worker.dart:
import 'package:js/js.dart';
main(){
allowInterop(doComputation);
}
#JS('doComputation')
String doComputation(String computationInput) {
// Replace this with your actual computation.
final String computationOutput = "output";
return computationOutput;
}
Compile it using:
$ dart compile js web_worker.dart -o webWorker.js
Manually edit webWorker.js, the JS file generated by the compiler:
Delete this line at the top of the file:
(function dartProgram() {
and the line at the bottom of the file with the corresponding closing brace:
})();
I don't understand what's going on here but I found the Javascript version of the function doComputation() defined in webWorker.js as a property of the object "A".
I defined a wrapper at the top of the file like this:
function doComputation(computationInput) {
return A.doComputation(computationInput)
}
and then I was able to use the file with JsIsolatedWorker like this:
final bool loaded =
await JsIsolatedWorker().importScripts(['../web/webWorker.js']);
if (loaded) {
final String computationResult = await JsIsolatedWorker()
.run(functionName: 'doComputation', arguments: computationInput);
} else {
debugPrint('Web worker is not available');
}
If someone who understands this better can elaborate or improve on this solution, that would be great. I don't really have any idea what I'm doing. I'm just posting this to hopefully help other people save time in the future by sharing what worked for me.
You can use js package to call JavaScript APIs from Dart code, or vice versa. To make a Dart function callable from JavaScript by name, use a setter annotated with #JS().
#JS()
library callable_function;
import 'package:js/js.dart';
/// Allows assigning a function to be callable from `window.functionName()`
#JS('functionName')
external set _functionName(void Function() f);
/// Allows calling the assigned function from Dart as well.
#JS()
external void functionName();
void _someDartFunction() {
print('Hello from Dart!');
}
void main() {
_functionName = allowInterop(_someDartFunction);
}
JavaScript code may now call functionName() or window.functionName().
Check google chartjs https://github.com/google/chartjs.dart/tree/master/example for a complete example.
From dart2js "Helping dart2js generate better code" there is a tip :
Don’t worry about the size of your app’s included libraries. The dart2js compiler performs tree shaking to omit unused classes, functions, methods, and so on. Just import the libraries you need, and let dart2js get rid of what you don’t need.
Related to this post https://stackoverflow.com/a/21124252/3733730.
You can do this instead by using the package dart2js
one make a program for your main.dart dart2js where the function or command you wanted to make is there, then create a separate dart file what function you wanted to call, and it will fix your problem, it is a separate file but will only execute one function that you needed to do so and that is the separate file

How to provide TypeScript annotation to existing global function

I'm considering adding TypeScript type annotations to an existing project.
I'm having trouble providing an external declaration file for a very simple example:
program.ts:
/// <reference path="types.d.ts"/>
function greet (p) {
console.log(p.name);
}
var x = {name: 'Mary'};
greet(x);
types.d.ts:
interface Person {
height?: number,
name: string
}
declare function greet (p: Person): void;
I expected this to work but I'm getting the following error:
program.ts(3,10): error TS2384: Overload signatures must all be ambient or non-ambient.
It seems to think that the function definition is an overload and not the implementation of a previous declaration.
What is the right way to add a type to the greet function?
Requirement: the program.ts should be plain JavaScript, e.g., free from any type annotations.
This isn't supported or allowed by the language. Essentially the code is doing...
interface Person {
height?: number,
name: string
}
declare function greet(p: Person): void;
function greet(p: any): void {
console.log(p.name);
}
So you get that error for defining a function and ambient function with the same name.
What is the right way to add a type to the greet function?
It's to do this:
interface Person {
height?: number,
name: string
}
function greet(p: Person): void {
console.log(p.name);
}
Requirement: the program.ts should be plain JavaScript, e.g., free from any type annotations.
This isn't possible without changing the code in program.ts. One possibility is to change program.ts to program.js then describe program.js with a declaration file for use in other files. That would only mean other files using program.js could benefit from knowing the type and structure of that file, but it wouldn't stop you from making mistakes in program.js.
Note that the main purpose of definition files is to provide type information for code found in .js files—not .ts files.

How to call a JS function from Java Rhino

So I've been looking and I found some other questions in stackoverflow but they weren't explained and I didn't understand much. I'm trying to execute functions from a .js file. One of the functions is:
function getRSAKey(mod, exp, pass) {
pubKey = RSA.getPublicKey(mod,exp);
encrypted = RSA.encrypt(pass, pubKey);
return encrypted;
}
As you see this function calls other functions, this is quite a big file and there's no way I can "translate" it to Java, so I have to call the .js file within it. So far I think I need to create an String with the .js file, so that's what I have in my .java file:
BufferedReader script = new BufferedReader(new FileReader("rsa.js"));
Context context = Context.enter();
ScriptableObject scope = context.initStandardObjects();
How can I do to call the function getRSAKey with some given paramaters? Also I should handle the return in the .java file!
Thanks
Edit: I forgot to say that the script uses http://silentmatt.com/biginteger/ the class provided in the link. I was able to execute a script, but it says that 'ReferenceError: "BigInteger" is not defined.'

Declaring a JS library for use with TypeScript

There are many threads for similar issues, but as far as I can tell this one is unique.
I'm using jQuery Address plugin in my app and would like to use it in a TypeScript file. Unfortunately there is no DefinitelyTyped script available for the library. When I try to use jQuery.address, I get:
The property 'address' does not exist on value of type 'jQueryStatic'
Per this thread, I've tried to define address inside of jquery.d.ts:
interface JQueryStatic {
address(options): any;
...
}
And I think this seems to work for $.address(); but not for any of address' methods. I've also tried to create my own .d.ts file per this thread, but still no luck. And I tried using declare in a .d.ts file. No luck.
The only method that I need to use is the parameter method...
$.address.parameter('param', 1);
In which case I get:
The property 'parameter' does not exist on value of type 'address'
Any ideas on how I can resolve this?
edit: I'm working in a Visual Studio C# .net environment, if that helps.
You should not need to edit jquery.d.ts itself; put these definitions in their own file so they can be maintained properly. Something minimal would be like this:
// For methods on e.g. $('a')
interface JQuery {
address(callback?: () => void): JQuery;
}
// For methods on $
interface JQueryStatic {
address: JQueryAddressStatic;
}
interface JQueryAddressStatic {
(): JQuery;
parameter(name: string): string;
parameter(name: string, value: string, append?: boolean): JQuery;
}
The following goes inside jquery.d.ts:
interface JQueryStatic {
address(options): JQueryAddress;
}
interface JQueryAddress {
parameter(name, value): any;
}
Hope that helps!

Categories

Resources