简体   繁体   中英

Typescript types for code that is not imported by typescript?

This is an issue with an Angular app, but I don't believe this is an angular-specific issue.

I'm working on an Angular 7 app, and I'm working with a few libraries that are imported via script tags on the front end from other sources (Stripe, recaptcha, googletags, etc). I'll use Stripe as an example here, because Stripe absolutely requires that the front end library be imported from Stripe.js by the client for PCI compliance, so from source server side is not an option.

I've installed the types for Stripe from DefinitelyTyped. If I add declare let Stripe: any; and use Stripe in a component, it works, but of course it is not type safe. If I omit the declaration, VSCode finds the types fine, and the editor catches type errors, but it won't compile, ( error TS2304: Cannot find name 'Stripe'. ) presumable because I have no import statement for Stripe.

Is there any way to hint to TypeScript that it should use the types from DefinitelyTyped to catch type errors, without importing the Stripe library itself?

Edit: I take back what I said about not thinking this is Angular specific. I now think this might have something to do with the angular compilation process.

I had the same problem in the past, and I also find it impossible to import the Type Definition files using import without importing the actual module.

So, what I did is, I copied the Type Definition file (usually index.d.ts ) into my codebase.

After that, you could do something like:

import {SomeType} from "sometype.d.ts"
declare let ObjectImportedFromHTMLScriptTag: SomeType;

Then, you could use the imported object without breaking type safety.

我的问题的答案似乎在这里: @ types / googlemaps / index.d.ts'不是模块也就是说,我可以使用三斜杠指令,或在root typings.d.ts文件中声明模块。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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