Skip to content

Instantly share code, notes, and snippets.

@ultrox
Last active December 7, 2023 08:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ultrox/42f8277d08b0ebd1638181e3a1703b93 to your computer and use it in GitHub Desktop.
Save ultrox/42f8277d08b0ebd1638181e3a1703b93 to your computer and use it in GitHub Desktop.
Can't seams to alight the types when folding the port. My expectation is for port to be number, which it is, but I'm getting an error telling me it can't be assigned to Error.
import type { PathLike } from "fs";
import fs from "fs";
import path, { parse } from "path";
import * as E from "fp-ts/lib/Either";
import { pipe } from "fp-ts/function";
import { object } from "firebase-functions/v1/storage";
import { objectHasProp } from "~/lib/utils";
import * as IE from "fp-ts/IOEither";
main();
function main() {
pipe(
getPort(new URL(configPath)),
E.fold(
(err) => err,
(port) => port // HERE: number is not assignable to type Error
),
);
}
function getPort(p: PathLike) {
return pipe(
readFileSync(p, "utf-8"),
E.flatMap(parseJSON),
E.flatMap(parseConfig),
);
}
function parseConfig(config: unknown): E.Either<Error, number> {
if (objectHasProp(config, "port")) {
return E.right(config.port as number);
} else {
return E.left(new Error("No Port"));
}
}
function readFileSync(path: PathLike, encoding: BufferEncoding) {
return tryCatch(() => fs.readFileSync(path, encoding));
}
function parseJSON(str: string): E.Either<Error, unknown> {
return tryCatch(() => JSON.parse(str));
}
function tryCatch<T>(f: () => T): E.Either<Error, T> {
try {
return E.right(f());
} catch (err) {
return E.left(err instanceof Error ? err : new Error(String(err)));
}
}
export const objectHasProp = <T extends string>(
v: unknown,
hasProp: T,
): v is { [K in T]: unknown } => {
return typeof v === "object" && v !== null && hasProp in v;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment