[Typescript] Only Type import or export
import type
only imports declarations to be used for type annotations and declarations. It always gets fully erased, so there’s no remnant of it at runtime. Similarly, export type
only provides an export that can be used for type contexts, and is also erased from TypeScript’s output.
import type { SomeThing } from "./some-module.js";
export type { SomeThing };
// actual code with JSDoc comments
/* eslint-disable promise/always-return */
import { useEffect } from 'react';
import Deferred from './deferred';
/**
*
* @param {() => Promise} getData
* @param {{
stateName: string;
otherStatesToMonitor?: unknown[];
setter: (arg: x) => void;
}} options
@return {void}
*/
export function useAsyncDataEffect(getData, options) {
let cancelled = false;
const { setter, stateName } = options;
useEffect(() => {
const d = new Deferred();
getData()
.then((jsonData) => {
if (cancelled) return;
else d.resolve(jsonData);
})
.catch(d.reject);
d.promise
.then((data) => {
if (!cancelled) {
console.info(
'%c Updating state: ' + stateName,
'background: green; color: white; display: block;',
);
setter(data);
}
})
.catch(console.error);
return () => {
cancelled = true;
};
}, [...(options.otherStatesToMonitor || []), stateName]);
}
We can import the type only:
import type {useAsyncDataEffect} from "./src/utils/api"
But we cannot use type as value:
useAsyncDataEffect() // Error: 'useAsyncDataEffect' cannot be used as a value because it was imported using 'import type'.