Skip to content

Commit

Permalink
refactor: reduce number of leaked anys (facebook#7465)
Browse files Browse the repository at this point in the history
  • Loading branch information
Josh-Cena authored May 22, 2022
1 parent 6e62bba commit 89b0fff
Show file tree
Hide file tree
Showing 39 changed files with 121 additions and 89 deletions.
6 changes: 5 additions & 1 deletion __tests__/validate-package-json.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,11 @@ type PackageJsonFile = {
async function getPackagesJsonFiles(): Promise<PackageJsonFile[]> {
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})),
),
);
}

Expand Down
6 changes: 5 additions & 1 deletion __tests__/validate-tsconfig.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,11 @@ type TsconfigFile = {
async function getTsconfigFiles(): Promise<TsconfigFile[]> {
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})),
),
);
}

Expand Down
26 changes: 13 additions & 13 deletions packages/create-docusaurus/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ async function askForPackageManagerChoice(): Promise<PackageManager> {
.map((p) => ({title: p, value: p}));

return (
await prompts(
(await prompts(
{
type: 'select',
name: 'packageManager',
Expand All @@ -77,7 +77,7 @@ async function askForPackageManagerChoice(): Promise<PackageManager> {
logger.info`Falling back to name=${defaultPackageManager}`;
},
},
)
)) as {packageManager: PackageManager}
).packageManager;
}

Expand Down Expand Up @@ -203,7 +203,7 @@ async function getGitCommand(gitStrategy: GitStrategy): Promise<string> {
case 'copy':
return 'git clone --recursive --depth 1';
case 'custom': {
const {command} = await prompts(
const {command} = (await prompts(
{
type: 'text',
name: 'command',
Expand All @@ -215,7 +215,7 @@ async function getGitCommand(gitStrategy: GitStrategy): Promise<string> {
logger.info`Falling back to code=${'git clone'}`;
},
},
);
)) as {command: string};
return command ?? 'git clone';
}
case 'deep':
Expand Down Expand Up @@ -245,7 +245,7 @@ async function getSiteName(
}
return reqName;
}
const {siteName} = await prompts(
const {siteName} = (await prompts(
{
type: 'text',
name: 'siteName',
Expand All @@ -259,7 +259,7 @@ async function getSiteName(
process.exit(1);
},
},
);
)) as {siteName: string};
return siteName;
}

Expand Down Expand Up @@ -324,7 +324,7 @@ async function getSource(
const template = cliOptions.gitStrategy
? 'Git repository'
: (
await prompts(
(await prompts(
{
type: 'select',
name: 'template',
Expand All @@ -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',
Expand All @@ -359,7 +359,7 @@ async function getSource(
process.exit(1);
},
},
);
)) as {gitRepoUrl: string};
let strategy = cliOptions.gitStrategy;
if (!strategy) {
({strategy} = await prompts(
Expand Down Expand Up @@ -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',
Expand All @@ -418,7 +418,7 @@ async function getSource(
process.exit(1);
},
},
);
)) as {templateDir: string};
return {
type: 'local',
path: templateDir,
Expand All @@ -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`);
Expand Down
14 changes: 9 additions & 5 deletions packages/docusaurus-mdx-loader/src/loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,16 +92,20 @@ 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';
}

// TODO implementation can be completed/enhanced
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(', ')}]`;
}
Expand All @@ -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;
})
Expand Down Expand Up @@ -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 =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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}}},
Expand Down
2 changes: 2 additions & 0 deletions packages/docusaurus-module-type-aliases/src/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof Loadable>;
};
const routes: RouteConfig[];
export default routes;
Expand Down
8 changes: 6 additions & 2 deletions packages/docusaurus-plugin-content-blog/src/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down Expand Up @@ -101,7 +105,7 @@ const PluginOptionSchema = Joi.object<PluginOptions>({
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],
),
},
Expand Down
4 changes: 2 additions & 2 deletions packages/docusaurus-plugin-content-docs/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> {
Expand All @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion packages/docusaurus-plugin-content-docs/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ export default async function pluginContentDocs(
.command(command)
.arguments('<version>')
.description(commandDescription)
.action((version) => {
.action((version: unknown) => {
cliDocsVersionCommand(version, options, context);
});
},
Expand Down
2 changes: 1 addition & 1 deletion packages/docusaurus-plugin-content-docs/src/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ const OptionsSchema = Joi.object<PluginOptions>({
Joi.function(),
// Convert boolean values to functions
Joi.alternatives().conditional(Joi.boolean(), {
then: Joi.custom((val) =>
then: Joi.custom((val: boolean) =>
val ? DefaultNumberPrefixParser : DisabledNumberPrefixParser,
),
}),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ async function readVersionsFile(
): Promise<string[] | null> {
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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,9 @@ function BrowserOnlyReactJson(props: ReactJsonViewProps) {
return (
<BrowserOnly>
{() => {
// 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 <ReactJson {...props} />;
}}
</BrowserOnly>
Expand Down
2 changes: 1 addition & 1 deletion packages/docusaurus-plugin-pwa/src/registerSw.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
}
2 changes: 1 addition & 1 deletion packages/docusaurus-plugin-sitemap/src/createSitemap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
6 changes: 4 additions & 2 deletions packages/docusaurus-theme-classic/src/theme/Tabs/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<TabItemProps> {
return typeof comp.props.value !== 'undefined';
function isTabItem(
comp: ReactElement<object>,
): comp is ReactElement<TabItemProps> {
return 'value' in comp.props;
}

function TabsComponent(props: Props): JSX.Element {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -196,17 +196,15 @@ 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<any>(null);
const collapsibleRef = useRef<HTMLElement>(null);

useCollapseAnimation({collapsibleRef, collapsed, animation});

return (
<As
// @ts-expect-error: the "too complicated type" is produced from
// "CollapsibleElementType" being a huge union
ref={collapsibleRef}
ref={collapsibleRef as RefObject<never>} // Refs are contravariant, which is not expressible in TS
style={disableSSRStyle ? undefined : getSSRStyle(collapsed)}
onTransitionEnd={(e: React.TransitionEvent) => {
if (e.propertyName !== 'height') {
Expand Down
2 changes: 1 addition & 1 deletion packages/docusaurus-theme-common/src/utils/docsUtils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
2 changes: 1 addition & 1 deletion packages/docusaurus-theme-translations/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
2 changes: 1 addition & 1 deletion packages/docusaurus-utils-validation/src/JoiFrontMatter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()};
}
Expand Down
6 changes: 3 additions & 3 deletions packages/docusaurus-utils-validation/src/validationSchemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand All @@ -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();
}
Expand Down
5 changes: 3 additions & 2 deletions packages/docusaurus-utils/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading

0 comments on commit 89b0fff

Please sign in to comment.