简体   繁体   English

Typescript 在当前 scope 中调用 javascript function

[英]Typescript call a javascript function in current scope

I'm migrating a project from JS to Typescript.我正在将一个项目从 JS 迁移到 Typescript。 But new TS class should coexist with previous JS.但是新的 TS class 应该与以前的 JS 共存。 There is a function in scope called verifyActivityChange().在 scope 中有一个名为 verifyActivityChange() 的 function。 In javascript this function has been declared in the app.js file and can be called from anywhere.在 javascript 中,此 function 已在 app.js 文件中声明,可以从任何地方调用。

How do I call this function from a Typescript class?如何从 Typescript class 调用这个 function?

In some TS file I was able to do在一些 TS 文件中我能够做到

    // @ts-ignore
    import * as appjs from "./app.js";
    appjs.verifyActivityChange();

Note sure if this is correct since I had to ignore compilation error.请注意这是否正确,因为我不得不忽略编译错误。 But if I'm doing the same process within a class I have an error appjs dosn't have a constructor.但是,如果我在 class 中执行相同的过程,则会出现错误 appjs dosn't have a constructor。

Edit How do I call the function from the class编辑如何从 class 调用 function

    import {verifyActivityChange} from "./app.js";
    
    export class ViewController {
    
        public update(){
    
    verifyActivityChange(); //how can I call this function ? it's on my page DOM

    }

}

You can import JS files in TS code, but you have to do inform the compiler that you are trying to do this.您可以在 TS 代码中导入 JS 文件,但您必须通知编译器您正在尝试这样做。 You can either compile with the --allowJs option (read more here ) or specify this in the tsconfig.json file, read morehere )您可以使用--allowJs选项进行编译( 在此处阅读更多内容)或在tsconfig.json文件中指定此选项,在此处阅读更多内容)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM