简体   繁体   English

将JS函数实现为typescript

[英]implementing JS function into typescript

I'm implementing a JS function into typescript, it works fine on JS, but on TS, I get: 我正在将一个JS函数实现为typescript,它在JS上工作正常,但在TS上,我得到:

[ts] Cannot find name 'PasscodeAuth'. [ts]找不到名字'PasscodeAuth'。 Did you mean 'passcodeAuth'? 你是说'passcodeAuth'吗?

function passcodeAuth() {
  return PasscodeAuth.isSupported()
    .then(() => {
      return PasscodeAuth.authenticate()
    })
    .then(success => {
      AlertIOS.alert('Authenticated Successfully');
    })
    .catch(error => {
      console.log(error)
      AlertIOS.alert(error.message);
    });
}

So is not an import, or defined anywhere, but it works on JS, so how can I make it recognizable for TS? 所以不是导入,也不是在任何地方定义,但它适用于JS,那么如何让它可以被TS识别呢? On JS, I can name my parameter as any word on JS and it will have isSupported and authenticate, even though is now a real parameter? 在JS上,我可以将我的参数命名为JS上的任何单词,它将具有isSupported和authenticate,即使现在是一个真正的参数?

thanks! 谢谢!

Putting aside the issue of if PasscodeAuth actually exists, you can inform typescript of it by using a declare statement. 抛开PasscodeAuth实际存在的问题,您可以使用declare语句通知typescript。 For your example: 对于你的例子:

// Put this at the root level of the file that uses PasscodeAuth
declare const PasscodeAuth: any;

That will declare PasscodeAuth as a variable with type any . 这将声明PasscodeAuth为类型为any的变量。 You can then use it in your file without errors related to that variable, but since it's typed as an any , you won't be getting any type safety from it. 然后,您可以在文件中使用它而不会出现与该变量相关的错误,但由于它是作为any键入的,因此您不会从中获得任何类型安全性。 If you happen to know the type for it, you can specify a more specific type instead of any . 如果您碰巧知道它的类型,则可以指定更具体的类型而不是any类型。

A declare statement is only a type annotation, so that line won't actually have any effect on the emitted javascript code. declare语句只是一个类型注释,因此该行实际上不会对发出的javascript代码产生任何影响。 You mentioned that your code already works as-is, despite the typescript errors, so a declaration sounds like exactly what you need. 你提到你的代码已经按原样运行,尽管有打字稿错误,所以声明听起来就像你需要的那样。

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

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