Skip to content

Commit

Permalink
chore: Enable full strict mode for tsc
Browse files Browse the repository at this point in the history
  • Loading branch information
PartMan7 committed Nov 24, 2024
1 parent eeccbea commit 2165907
Show file tree
Hide file tree
Showing 14 changed files with 45 additions and 32 deletions.
4 changes: 2 additions & 2 deletions src/cache/persisted.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ export function usePersistedCache<T extends keyof CacheTypes>(cacheKey: T): Cach
const get = (): CacheTypes[T] => {
const stored = flatCache.get<CacheTypes[T]>('value');
if (typeof stored === 'undefined') {
flatCache.set('value', defaults[cacheId]);
return defaults[cacheId];
flatCache.set('value', defaults[cacheKey]);
return defaults[cacheKey];
} else return stored;
};
const set = (value: CacheTypes[T]): void => {
Expand Down
2 changes: 1 addition & 1 deletion src/cache/reset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@ export function resetCache(...keys: CacheKeys) {
(keys.length ? keys : (Object.keys(cache) as CacheKeys)).forEach(cacheKey => {
// eslint-disable-next-line import/namespace -- cache key checked with the CacheKeys type
const cachedValue = cache[cacheKey];
Object.keys(cachedValue).forEach(key => delete cachedValue[key]);
Object.keys(cachedValue).forEach(key => delete cachedValue[key as keyof typeof cachedValue]);
});
}
4 changes: 2 additions & 2 deletions src/database/quotes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const schema = new mongoose.Schema({
rawText: {
type: String,
required: true,
default: function () {
default: function (this: Model) {
return (this.quote as string)
.toLowerCase()
.replace(/[^a-zA-Z0-9]+/g, ' ')
Expand All @@ -28,7 +28,7 @@ const schema = new mongoose.Schema({
addedById: {
type: String,
required: true,
default: function () {
default: function (this: Model) {
return toId(this.addedBy);
},
},
Expand Down
6 changes: 4 additions & 2 deletions src/discord/handlers/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@ export default async function messageHandler(interaction: Interaction): Promise<
try {
await command.run(interaction);
} catch (err) {
interaction.reply({ content: err.message, ephemeral: true });
if (err.name !== 'ChatError') log(err);
if (err instanceof Error) {
interaction.reply({ content: err.message, ephemeral: true });
if (err.name !== 'ChatError') log(err);
}
}
}
7 changes: 4 additions & 3 deletions src/i18n/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import English from '@/i18n/english';
import Hindi from '@/i18n/hindi';
import { ChatError } from '@/utils/chatError';

import type { TranslationFn } from '@/i18n/types';
import type { TextEntries, TranslationFn } from '@/i18n/types';

export const LanguageMap = {
english: English,
Expand All @@ -17,9 +17,10 @@ export function i18n(language: keyof typeof LanguageMap = 'english'): Translatio
const translations = LanguageMap[language];
const fallback = LanguageMap['english'];
return (lookup, variables = {}) => {
const [l1, l2] = lookup.split('.') as [string] | [string, string];
const [l1, l2] = lookup.split('.') as TextEntries[string];
const base: string | string[] | undefined = l2
? (translations[l1]?.[l2] ?? fallback[l1]?.[l2])
? // @ts-expect-error -- Easier to fallback
(translations[l1]?.[l2] ?? fallback[l1]?.[l2])
: (translations[l1] ?? fallback[l1]);
if (!base) throw new ChatError('Translations not found!');
if (Array.isArray(base)) return applyVariables(base.random(), variables);
Expand Down
10 changes: 7 additions & 3 deletions src/i18n/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,16 @@ import type refText from '@/i18n/english';

export type Translations = typeof refText;

export type TextEntries = {
[key in keyof Translations as string]: Translations[key] extends Record<string, string | string[]>
? [key, keyof Translations[key] & string]
: [key];
};

export type TextMap = {
[key in keyof Translations as Translations[key] extends Record<string, string | string[]>
? `${key}.${keyof Translations[key] & string}`
: key]: string | string[];
};

export type TextLookup = keyof TextMap;

export type TranslationFn = (lookup: TextLookup, variables?: Record<string, string | number>) => string;
export type TranslationFn = (lookup: keyof TextMap, variables?: Record<string, string | number>) => string;
2 changes: 1 addition & 1 deletion src/ps/commands/games.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -410,7 +410,7 @@ const metaCommands: PSCommand = {
},
};

export const command = [
export const command: PSCommand[] = [
...gameCommands,
metaCommands,
{
Expand Down
2 changes: 1 addition & 1 deletion src/ps/commands/quotes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import type { CSSProperties, ReactElement, ReactNode } from 'react';

type QuoteCollection = [index: number, quote: string][];

function Entry({ name, children }) {
function Entry({ name, children }: { name: string; children: ReactNode }) {
return (
<li>
<b>{name}</b>: {children}
Expand Down
10 changes: 7 additions & 3 deletions src/types/web.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
import type { Request, Response } from 'express';
import type { ReactElement } from 'react';

export type RouteHandler = (req: Request, res: Response & { render: Render }) => void;
export type UIRouteHandler = (
req: Request,
res: { [key in keyof Response as key extends 'render' ? never : key]: Response[key] } & { render: Render }
) => void;

// Note: This isn't the actual type that's imported, but since we override render to support JSX...
export type APIRoute = {
handler: RouteHandler;
handler: (req: Request, res: Response) => void;
verb?: 'get' | 'post';
};

export type UIRoute = {
handler: RouteHandler;
handler: (req: Request, res: Response) => void;
};

export type Render = (jsx: ReactElement, title: string, hydrate: boolean) => Promise<Response>;
2 changes: 1 addition & 1 deletion src/utils/chatError.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export class ChatError extends Error {
constructor(args) {
constructor(args: string) {
super(args);
this.name = this.constructor.name;
}
Expand Down
4 changes: 2 additions & 2 deletions src/utils/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ function dimText(str: string): string {
const logStream = fsSync.createWriteStream(fsPath('..', 'logs', 'logs.txt'), { flags: 'a' });
const errLogStream = fsSync.createWriteStream(fsPath('..', 'logs', 'err-logs.txt'), { flags: 'a' });

export function log(...args): void {
export function log(...args: unknown[]): void {
const timestamp = `[${new Date().toISOString()}]`;
args.forEach(arg => {
const logStr = inspect(arg, { depth: 3 });
Expand All @@ -20,7 +20,7 @@ export function log(...args): void {
console.log(dimText(timestamp), ...args);
}

export function deepLog(...args): void {
export function deepLog(...args: unknown[]): void {
const timestamp = `[${new Date().toISOString()}]`;
args.forEach(arg => {
const logStr = inspect(arg, { depth: null });
Expand Down
12 changes: 8 additions & 4 deletions src/web/api/quotes/[room].ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import { getAllQuotes } from '@/database/quotes';

import type { RouteHandler } from '@/types/web';
import type { RequestHandler } from 'express';

export const handler: RouteHandler = async (req, res) => {
export const handler: RequestHandler = async (req, res) => {
const { room } = req.params as { room: string };
const quotes = await getAllQuotes(room);
if (!quotes.length) return res.sendStatus(404);
return res.json(quotes);
if (!quotes.length) {
// https://github.com/microsoft/TypeScript/issues/12871
res.sendStatus(404);
return;
}
res.json(quotes);
};
6 changes: 3 additions & 3 deletions src/web/ui/test.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { RouteHandler } from '@/types/web';
import type { UIRouteHandler } from '@/types/web';

const Div = () => <div>Test content here; fully static</div>;

export const handler: RouteHandler = (req, res) => {
return res.render(<Div />, 'Test Title', false);
export const handler: UIRouteHandler = (req, res) => {
res.render(<Div />, 'Test Title', false);
};
6 changes: 2 additions & 4 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,8 @@
"noEmit": true, // We run PartBot with ts-node instead of a two-step process
"jsx": "react-jsx",
"module": "commonjs", // 'require' syntax makes HMR possible; 'import' doesn't
"esModuleInterop": true,
// Some strict mode patterns:
"strictBindCallApply": true,
"strictNullChecks": true,
"esModuleInterop": true, // allow default-importing stuff like path
"strict": true,
"paths": {
"@/secrets/*": ["./secrets/src/*"],
"@/*": ["./*"]
Expand Down

0 comments on commit 2165907

Please sign in to comment.