I am importing a simple JS file via script tag on an HTML page.
As I use jQuery on the website I've added // @ts-check to the top of the JS file, as well as jQuery types:
/**
* Modal Functionality
* @param {JQueryStatic} $ Provides jQuery types
*/
const example = ($) => ...
While jQuery types are correctly cast to $, I'm also using the Swiper library and include the library's JS via another script tag. For the sake of argument this could be any other externally imported library.
When using new Swiper('...') in the JS, TS scribbles lines underneath Swiper: Cannot find name 'Swiper'. I've added the following code to an adjacent TS file:
declare global {
interface Window {
Swiper: typeof import('swiper'); // swiper types imported from official package
}
}
let Swiper = window.Swiper;
Going back to my JS file, hovering over Swiper still reads Swiper: any. Shouldn't it reflect the types found from the imported package? Is the JS/TS file structure a problem? How do I get type annotations in a JS file?
Some library include types, some not. You need to install types for Swiper.
npm install --save-dev @types/swiper
After this you can import type in ts file
// index.d.ts
import Swiper from 'swiper';
declare global {
interface Window {
Swiper: Swiper;
}
}
Typescript look global type declaration by default at index.d.ts file.
To declare modules or extend window and global properties, you need to declare them in index.d.ts.