diff --git a/__tests__/validate-package-json.test.ts b/__tests__/validate-package-json.test.ts index 31bd4e8b5e8d..ef18176ecd92 100644 --- a/__tests__/validate-package-json.test.ts +++ b/__tests__/validate-package-json.test.ts @@ -28,7 +28,11 @@ type PackageJsonFile = { async function getPackagesJsonFiles(): Promise { const files = await Globby('packages/*/package.json'); return Promise.all( - files.map((file) => fs.readJSON(file).then((content) => ({file, content}))), + files.map((file) => + fs + .readJSON(file) + .then((content: PackageJsonFile['content']) => ({file, content})), + ), ); } diff --git a/__tests__/validate-tsconfig.test.ts b/__tests__/validate-tsconfig.test.ts index 7a80816b7a98..e69d170502ba 100644 --- a/__tests__/validate-tsconfig.test.ts +++ b/__tests__/validate-tsconfig.test.ts @@ -22,7 +22,11 @@ type TsconfigFile = { async function getTsconfigFiles(): Promise { const files = await Globby('packages/*/tsconfig.*'); return Promise.all( - files.map((file) => fs.readJSON(file).then((content) => ({file, content}))), + files.map((file) => + fs + .readJSON(file) + .then((content: TsconfigFile['content']) => ({file, content})), + ), ); } diff --git a/packages/create-docusaurus/src/index.ts b/packages/create-docusaurus/src/index.ts index cc9c9408ec30..c1f592cefcd1 100755 --- a/packages/create-docusaurus/src/index.ts +++ b/packages/create-docusaurus/src/index.ts @@ -65,7 +65,7 @@ async function askForPackageManagerChoice(): Promise { .map((p) => ({title: p, value: p})); return ( - await prompts( + (await prompts( { type: 'select', name: 'packageManager', @@ -77,7 +77,7 @@ async function askForPackageManagerChoice(): Promise { logger.info`Falling back to name=${defaultPackageManager}`; }, }, - ) + )) as {packageManager: PackageManager} ).packageManager; } @@ -203,7 +203,7 @@ async function getGitCommand(gitStrategy: GitStrategy): Promise { case 'copy': return 'git clone --recursive --depth 1'; case 'custom': { - const {command} = await prompts( + const {command} = (await prompts( { type: 'text', name: 'command', @@ -215,7 +215,7 @@ async function getGitCommand(gitStrategy: GitStrategy): Promise { logger.info`Falling back to code=${'git clone'}`; }, }, - ); + )) as {command: string}; return command ?? 'git clone'; } case 'deep': @@ -245,7 +245,7 @@ async function getSiteName( } return reqName; } - const {siteName} = await prompts( + const {siteName} = (await prompts( { type: 'text', name: 'siteName', @@ -259,7 +259,7 @@ async function getSiteName( process.exit(1); }, }, - ); + )) as {siteName: string}; return siteName; } @@ -324,7 +324,7 @@ async function getSource( const template = cliOptions.gitStrategy ? 'Git repository' : ( - await prompts( + (await prompts( { type: 'select', name: 'template', @@ -337,10 +337,10 @@ async function getSource( process.exit(1); }, }, - ) + )) as {template: Template | 'Git repository' | 'Local template'} ).template; if (template === 'Git repository') { - const {gitRepoUrl} = await prompts( + const {gitRepoUrl} = (await prompts( { type: 'text', name: 'gitRepoUrl', @@ -359,7 +359,7 @@ async function getSource( process.exit(1); }, }, - ); + )) as {gitRepoUrl: string}; let strategy = cliOptions.gitStrategy; if (!strategy) { ({strategy} = await prompts( @@ -393,7 +393,7 @@ async function getSource( strategy: strategy ?? 'deep', }; } else if (template === 'Local template') { - const {templateDir} = await prompts( + const {templateDir} = (await prompts( { type: 'text', name: 'templateDir', @@ -418,7 +418,7 @@ async function getSource( process.exit(1); }, }, - ); + )) as {templateDir: string}; return { type: 'local', path: templateDir, @@ -442,7 +442,7 @@ async function getSource( } async function updatePkg(pkgPath: string, obj: {[key: string]: unknown}) { - const pkg = await fs.readJSON(pkgPath); + const pkg = (await fs.readJSON(pkgPath)) as {[key: string]: unknown}; const newPkg = Object.assign(pkg, obj); await fs.outputFile(pkgPath, `${JSON.stringify(newPkg, null, 2)}\n`); diff --git a/packages/docusaurus-mdx-loader/src/loader.ts b/packages/docusaurus-mdx-loader/src/loader.ts index 06daefccf323..88fa1ecd5bdc 100644 --- a/packages/docusaurus-mdx-loader/src/loader.ts +++ b/packages/docusaurus-mdx-loader/src/loader.ts @@ -92,8 +92,12 @@ async function readMetadataPath(metadataPath: string) { * * `{image: "./myImage.png"}` => `{image: require("./myImage.png")}` */ -function createAssetsExportCode(assets: {[key: string]: unknown}) { - if (Object.keys(assets).length === 0) { +function createAssetsExportCode(assets: unknown) { + if ( + typeof assets !== 'object' || + !assets || + Object.keys(assets).length === 0 + ) { return 'undefined'; } @@ -101,7 +105,7 @@ function createAssetsExportCode(assets: {[key: string]: unknown}) { function createAssetValueCode(assetValue: unknown): string | undefined { if (Array.isArray(assetValue)) { const arrayItemCodes = assetValue.map( - (item) => createAssetValueCode(item) ?? 'undefined', + (item: unknown) => createAssetValueCode(item) ?? 'undefined', ); return `[${arrayItemCodes.join(', ')}]`; } @@ -119,7 +123,7 @@ function createAssetsExportCode(assets: {[key: string]: unknown}) { const assetEntries = Object.entries(assets); const codeLines = assetEntries - .map(([key, value]) => { + .map(([key, value]: [string, unknown]) => { const assetRequireCode = createAssetValueCode(value); return assetRequireCode ? `"${key}": ${assetRequireCode},` : undefined; }) @@ -227,7 +231,7 @@ ${JSON.stringify(frontMatter, null, 2)}`; : undefined; const metadata = metadataJsonString - ? JSON.parse(metadataJsonString) + ? (JSON.parse(metadataJsonString) as {[key: string]: unknown}) : undefined; const assets = diff --git a/packages/docusaurus-mdx-loader/src/remark/headings/__tests__/index.test.ts b/packages/docusaurus-mdx-loader/src/remark/headings/__tests__/index.test.ts index 2f9683e6e8de..f671d6f517f8 100644 --- a/packages/docusaurus-mdx-loader/src/remark/headings/__tests__/index.test.ts +++ b/packages/docusaurus-mdx-loader/src/remark/headings/__tests__/index.test.ts @@ -13,13 +13,14 @@ import removePosition from 'unist-util-remove-position'; import toString from 'mdast-util-to-string'; import visit from 'unist-util-visit'; import slug from '../index'; +import type {Plugin} from 'unified'; -function process(doc, plugins = []) { +function process(doc: string, plugins: Plugin[] = []) { const processor = remark().use({plugins: [...plugins, slug]}); return removePosition(processor.runSync(processor.parse(doc)), true); } -function heading(label, id) { +function heading(label: string, id: string) { return u( 'heading', {depth: 2, data: {id, hProperties: {id}}}, diff --git a/packages/docusaurus-module-type-aliases/src/index.d.ts b/packages/docusaurus-module-type-aliases/src/index.d.ts index a000e03f2c35..ccb4bf5706fc 100644 --- a/packages/docusaurus-module-type-aliases/src/index.d.ts +++ b/packages/docusaurus-module-type-aliases/src/index.d.ts @@ -35,9 +35,11 @@ declare module '@generated/registry' { declare module '@generated/routes' { import type {RouteConfig as RRRouteConfig} from 'react-router-config'; + import type Loadable from 'react-loadable'; type RouteConfig = RRRouteConfig & { path: string; + component: ReturnType; }; const routes: RouteConfig[]; export default routes; diff --git a/packages/docusaurus-plugin-content-blog/src/options.ts b/packages/docusaurus-plugin-content-blog/src/options.ts index baf927b8c671..f6fa74e726bc 100644 --- a/packages/docusaurus-plugin-content-blog/src/options.ts +++ b/packages/docusaurus-plugin-content-blog/src/options.ts @@ -13,7 +13,11 @@ import { URISchema, } from '@docusaurus/utils-validation'; import {GlobExcludeDefault} from '@docusaurus/utils'; -import type {PluginOptions, Options} from '@docusaurus/plugin-content-blog'; +import type { + PluginOptions, + Options, + FeedType, +} from '@docusaurus/plugin-content-blog'; import type {OptionValidationContext} from '@docusaurus/types'; export const DEFAULT_OPTIONS: PluginOptions = { @@ -101,7 +105,7 @@ const PluginOptionSchema = Joi.object({ Joi.alternatives().conditional( Joi.string().equal('all', 'rss', 'atom', 'json'), { - then: Joi.custom((val) => + then: Joi.custom((val: FeedType | 'all') => val === 'all' ? ['rss', 'atom', 'json'] : [val], ), }, diff --git a/packages/docusaurus-plugin-content-docs/src/cli.ts b/packages/docusaurus-plugin-content-docs/src/cli.ts index 11fc39b2c400..7156d4c6e49a 100644 --- a/packages/docusaurus-plugin-content-docs/src/cli.ts +++ b/packages/docusaurus-plugin-content-docs/src/cli.ts @@ -53,7 +53,7 @@ async function createVersionedSidebarFile({ // Tests depend on non-default export for mocking. export async function cliDocsVersionCommand( - version: string, + version: unknown, {id: pluginId, path: docsPath, sidebarPath}: PluginOptions, {siteDir, i18n}: LoadContext, ): Promise { @@ -70,7 +70,7 @@ export async function cliDocsVersionCommand( } // Load existing versions. - let versions = []; + let versions: string[] = []; const versionsJSONFile = getVersionsFilePath(siteDir, pluginId); if (await fs.pathExists(versionsJSONFile)) { versions = await fs.readJSON(versionsJSONFile); diff --git a/packages/docusaurus-plugin-content-docs/src/index.ts b/packages/docusaurus-plugin-content-docs/src/index.ts index 422dfcbe3ea9..982895957382 100644 --- a/packages/docusaurus-plugin-content-docs/src/index.ts +++ b/packages/docusaurus-plugin-content-docs/src/index.ts @@ -100,7 +100,7 @@ export default async function pluginContentDocs( .command(command) .arguments('') .description(commandDescription) - .action((version) => { + .action((version: unknown) => { cliDocsVersionCommand(version, options, context); }); }, diff --git a/packages/docusaurus-plugin-content-docs/src/options.ts b/packages/docusaurus-plugin-content-docs/src/options.ts index 047f59ff3940..27b9118a718f 100644 --- a/packages/docusaurus-plugin-content-docs/src/options.ts +++ b/packages/docusaurus-plugin-content-docs/src/options.ts @@ -98,7 +98,7 @@ const OptionsSchema = Joi.object({ Joi.function(), // Convert boolean values to functions Joi.alternatives().conditional(Joi.boolean(), { - then: Joi.custom((val) => + then: Joi.custom((val: boolean) => val ? DefaultNumberPrefixParser : DisabledNumberPrefixParser, ), }), diff --git a/packages/docusaurus-plugin-content-docs/src/versions/files.ts b/packages/docusaurus-plugin-content-docs/src/versions/files.ts index 6b7464ee3049..f9ef69c82944 100644 --- a/packages/docusaurus-plugin-content-docs/src/versions/files.ts +++ b/packages/docusaurus-plugin-content-docs/src/versions/files.ts @@ -95,7 +95,7 @@ async function readVersionsFile( ): Promise { const versionsFilePath = getVersionsFilePath(siteDir, pluginId); if (await fs.pathExists(versionsFilePath)) { - const content = await fs.readJSON(versionsFilePath); + const content: unknown = await fs.readJSON(versionsFilePath); validateVersionNames(content); return content; } diff --git a/packages/docusaurus-plugin-debug/src/theme/DebugJsonView/index.tsx b/packages/docusaurus-plugin-debug/src/theme/DebugJsonView/index.tsx index e6d981234dde..d22d4a015b3c 100644 --- a/packages/docusaurus-plugin-debug/src/theme/DebugJsonView/index.tsx +++ b/packages/docusaurus-plugin-debug/src/theme/DebugJsonView/index.tsx @@ -19,8 +19,9 @@ function BrowserOnlyReactJson(props: ReactJsonViewProps) { return ( {() => { - // eslint-disable-next-line global-require, @typescript-eslint/no-var-requires - const ReactJson = require('react-json-view').default; + const {default: ReactJson} = + // eslint-disable-next-line global-require, @typescript-eslint/no-var-requires + require('react-json-view') as typeof import('react-json-view'); return ; }} diff --git a/packages/docusaurus-plugin-pwa/src/registerSw.ts b/packages/docusaurus-plugin-pwa/src/registerSw.ts index a215a656aa58..92252cc5177c 100644 --- a/packages/docusaurus-plugin-pwa/src/registerSw.ts +++ b/packages/docusaurus-plugin-pwa/src/registerSw.ts @@ -320,6 +320,6 @@ if (typeof window !== 'undefined') { addLegacyAppInstalledEventsListeners(); // Then try to register the SW using lazy/dynamic imports - registerSW().catch((e) => console.error('registerSW failed', e)); + registerSW().catch((e: unknown) => console.error('registerSW failed', e)); } } diff --git a/packages/docusaurus-plugin-sitemap/src/createSitemap.ts b/packages/docusaurus-plugin-sitemap/src/createSitemap.ts index 366714fd3f9b..052dee692014 100644 --- a/packages/docusaurus-plugin-sitemap/src/createSitemap.ts +++ b/packages/docusaurus-plugin-sitemap/src/createSitemap.ts @@ -35,7 +35,7 @@ export default async function createSitemap( } // https://github.com/staylor/react-helmet-async/pull/167 const meta = head[route]?.meta.toComponent() as unknown as - | ReactElement[] + | ReactElement<{name?: string; content?: string}>[] | undefined; return !meta?.some( (tag) => tag.props.name === 'robots' && tag.props.content === 'noindex', diff --git a/packages/docusaurus-theme-classic/src/theme/Tabs/index.tsx b/packages/docusaurus-theme-classic/src/theme/Tabs/index.tsx index 5ee9649ac226..e81a01d3fc5b 100644 --- a/packages/docusaurus-theme-classic/src/theme/Tabs/index.tsx +++ b/packages/docusaurus-theme-classic/src/theme/Tabs/index.tsx @@ -25,8 +25,10 @@ import styles from './styles.module.css'; // A very rough duck type, but good enough to guard against mistakes while // allowing customization -function isTabItem(comp: ReactElement): comp is ReactElement { - return typeof comp.props.value !== 'undefined'; +function isTabItem( + comp: ReactElement, +): comp is ReactElement { + return 'value' in comp.props; } function TabsComponent(props: Props): JSX.Element { diff --git a/packages/docusaurus-theme-common/src/components/Collapsible/index.tsx b/packages/docusaurus-theme-common/src/components/Collapsible/index.tsx index 8b88da3c8ceb..b6210a2b3660 100644 --- a/packages/docusaurus-theme-common/src/components/Collapsible/index.tsx +++ b/packages/docusaurus-theme-common/src/components/Collapsible/index.tsx @@ -196,9 +196,7 @@ function CollapsibleBase({ className, disableSSRStyle, }: CollapsibleBaseProps) { - // any because TS is a pain for HTML element refs, see https://twitter.com/sebastienlorber/status/1412784677795110914 - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const collapsibleRef = useRef(null); + const collapsibleRef = useRef(null); useCollapseAnimation({collapsibleRef, collapsed, animation}); @@ -206,7 +204,7 @@ function CollapsibleBase({ } // Refs are contravariant, which is not expressible in TS style={disableSSRStyle ? undefined : getSSRStyle(collapsed)} onTransitionEnd={(e: React.TransitionEvent) => { if (e.propertyName !== 'height') { diff --git a/packages/docusaurus-theme-common/src/utils/docsUtils.tsx b/packages/docusaurus-theme-common/src/utils/docsUtils.tsx index fd9cfb7ab141..45d92d093770 100644 --- a/packages/docusaurus-theme-common/src/utils/docsUtils.tsx +++ b/packages/docusaurus-theme-common/src/utils/docsUtils.tsx @@ -318,7 +318,7 @@ export function useDocRouteMetadata({ } // For now, the sidebarName is added as route config: not ideal! - const sidebarName = currentDocRoute.sidebar; + const sidebarName = currentDocRoute.sidebar as string; const sidebarItems = sidebarName ? versionMetadata.docsSidebars[sidebarName] diff --git a/packages/docusaurus-theme-translations/src/utils.ts b/packages/docusaurus-theme-translations/src/utils.ts index da931ef454f8..95cf7f4ec712 100644 --- a/packages/docusaurus-theme-translations/src/utils.ts +++ b/packages/docusaurus-theme-translations/src/utils.ts @@ -23,7 +23,7 @@ import type {TranslationFileContent} from '@docusaurus/types'; async function getPackageCodePath(packageName: string) { const packagePath = path.join(__dirname, '../..', packageName); const packageJsonPath = path.join(packagePath, 'package.json'); - const {main} = await fs.readJSON(packageJsonPath); + const {main} = (await fs.readJSON(packageJsonPath)) as {main: string}; const packageSrcPath = path.join(packagePath, path.dirname(main)); return packageSrcPath; } diff --git a/packages/docusaurus-utils-validation/src/JoiFrontMatter.ts b/packages/docusaurus-utils-validation/src/JoiFrontMatter.ts index 011bccd8796c..b09f528ec14d 100644 --- a/packages/docusaurus-utils-validation/src/JoiFrontMatter.ts +++ b/packages/docusaurus-utils-validation/src/JoiFrontMatter.ts @@ -11,7 +11,7 @@ const JoiFrontMatterString: Joi.Extension = { type: 'string', base: Joi.string(), // Fix Yaml that tries to auto-convert many things to string out of the box - prepare: (value) => { + prepare: (value: unknown) => { if (typeof value === 'number' || value instanceof Date) { return {value: value.toString()}; } diff --git a/packages/docusaurus-utils-validation/src/validationSchemas.ts b/packages/docusaurus-utils-validation/src/validationSchemas.ts index eea887bea2a5..8c6a10e9c00b 100644 --- a/packages/docusaurus-utils-validation/src/validationSchemas.ts +++ b/packages/docusaurus-utils-validation/src/validationSchemas.ts @@ -40,10 +40,10 @@ export const URISchema = Joi.alternatives( Joi.string().uri({allowRelative: true}), // This custom validation logic is required notably because Joi does not // accept paths like /a/b/c ... - Joi.custom((val, helpers) => { + Joi.custom((val: unknown, helpers) => { try { // eslint-disable-next-line no-new - new URL(val); + new URL(String(val)); return val; } catch { return helpers.error('any.invalid'); @@ -55,7 +55,7 @@ export const URISchema = Joi.alternatives( }); export const PathnameSchema = Joi.string() - .custom((val) => { + .custom((val: string) => { if (!isValidPathname(val)) { throw new Error(); } diff --git a/packages/docusaurus-utils/src/constants.ts b/packages/docusaurus-utils/src/constants.ts index a9a91394f48c..be9405eab9bd 100644 --- a/packages/docusaurus-utils/src/constants.ts +++ b/packages/docusaurus-utils/src/constants.ts @@ -17,8 +17,9 @@ export const NODE_MINOR_VERSION = parseInt( ); /** Docusaurus core version. */ -// eslint-disable-next-line global-require, @typescript-eslint/no-var-requires -export const DOCUSAURUS_VERSION = require('../package.json').version; +export const DOCUSAURUS_VERSION = + // eslint-disable-next-line global-require, @typescript-eslint/no-var-requires + (require('../package.json') as {version: string}).version; /** * Can be overridden with cli option `--out-dir`. Code should generally use diff --git a/packages/docusaurus-utils/src/markdownUtils.ts b/packages/docusaurus-utils/src/markdownUtils.ts index a902c6f58fa0..fd11f5e66708 100644 --- a/packages/docusaurus-utils/src/markdownUtils.ts +++ b/packages/docusaurus-utils/src/markdownUtils.ts @@ -280,7 +280,10 @@ This can happen if you use special characters in front matter values (try using } function unwrapMarkdownLinks(line: string): string { - return line.replace(/\[(?[^\]]+)\]\([^)]+\)/g, (match, p1) => p1); + return line.replace( + /\[(?[^\]]+)\]\([^)]+\)/g, + (match, p1: string) => p1, + ); } function addHeadingId( diff --git a/packages/docusaurus/src/babel/preset.ts b/packages/docusaurus/src/babel/preset.ts index 3dd351ef9ac5..3d842007757e 100644 --- a/packages/docusaurus/src/babel/preset.ts +++ b/packages/docusaurus/src/babel/preset.ts @@ -53,7 +53,8 @@ function getTransformOptions(isServer: boolean): TransformOptions { // better to explicitly specify the version so that it can reuse the // helper better. See https://github.com/babel/babel/issues/10261 // eslint-disable-next-line @typescript-eslint/no-var-requires, global-require - version: require('@babel/runtime/package.json').version, + version: (require('@babel/runtime/package.json') as {version: string}) + .version, regenerator: true, useESModules: true, // Undocumented option that lets us encapsulate our runtime, ensuring diff --git a/packages/docusaurus/src/client/PendingNavigation.tsx b/packages/docusaurus/src/client/PendingNavigation.tsx index 3c2cca17f7b8..24e1e38faa2d 100644 --- a/packages/docusaurus/src/client/PendingNavigation.tsx +++ b/packages/docusaurus/src/client/PendingNavigation.tsx @@ -70,7 +70,7 @@ class PendingNavigation extends React.Component { this.routeUpdateCleanupCb?.(); this.setState({nextRouteHasLoaded: true}); }) - .catch((e) => console.warn(e)); + .catch((e: unknown) => console.warn(e)); return false; } diff --git a/packages/docusaurus/src/client/preload.ts b/packages/docusaurus/src/client/preload.ts index e77ac998f58d..fec374ad4b6b 100644 --- a/packages/docusaurus/src/client/preload.ts +++ b/packages/docusaurus/src/client/preload.ts @@ -19,8 +19,5 @@ import {matchRoutes} from 'react-router-config'; export default function preload(pathname: string): Promise { const matches = matchRoutes(routes, pathname); - return Promise.all( - // @ts-expect-error: ComponentCreator injected this method. - matches.map((match) => match.route.component?.preload?.()), - ); + return Promise.all(matches.map((match) => match.route.component.preload?.())); } diff --git a/packages/docusaurus/src/client/theme-fallback/Loading/index.tsx b/packages/docusaurus/src/client/theme-fallback/Loading/index.tsx index 79a0823c3194..7d47419bb7b3 100644 --- a/packages/docusaurus/src/client/theme-fallback/Loading/index.tsx +++ b/packages/docusaurus/src/client/theme-fallback/Loading/index.tsx @@ -37,7 +37,7 @@ export default function Loading({ maxWidth: '50%', width: '100%', }}> -

{error.message}

+

{String(error)}