1

I currently using Angular 8 and trying to use someone script. I encounter a problem and lack of knowledge regarding this problem.

In the javascript its function work like this,

window.X = function() {
    var e = argument.length > 0...

How do I pass values into this Javascript function in Typescript?

2
  • 1
    You mean something like this?: window.X = (a, b) => { <code> }; Or I misunderstood something? Commented Oct 16, 2020 at 10:39
  • function add(x: number, y: number): number { return x + y; } Commented Oct 16, 2020 at 10:39

2 Answers 2

2

To handle external functions in TypeScript with proper typing, simply declare it somewhere before you use it. In TypeScript variable parameter length is typed as (...args: any[]) (or more strict typing in case the parameters all are of the same type).

Example:

  <script>
    // function defined in index.html
    window.X = function() {
      console.log('X', arguments.length);
    }
  </script>
// angular component
import { Component } from '@angular/core';

// declare external function with proper type
declare const X: (...args: any[]) => void;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  run(): void{
    // call the external function with multiple parameters
    X('a', 'b');
  }
}

Here's a working stackblitz: https://stackblitz.com/edit/angular-ivy-zdr8ca?file=src%2Findex.html

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

Comments

0

Every javaScript code is also valid TypeScript code. so your Function should run in Typescript as you mentioned it.

you can Pass values like in a normal Javascript function:

window.X = function(numberToAdd) {
    return numberToAdd + 5
}

TypeScript allows you to add Types to the passed Values and to the return value of the function. Adding a Type to a passed Value would look like this:

window.X = function(numberToAdd: number) {
    return numberToAdd + 5
}

Which would result in a Typescript error if you would try to pass a String to the function

Adding a return Type to the function would look like this:

window.X = function(numberToAdd): number {
    return numberToAdd + 5
}

Which would result in a error if you would try to access values that a number does not have like

X(5).length

Such Typescript errors allow you to see mistakes in your Code before running it and therefore can prevent lots of bugs.

Comments

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.