npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@sealcode/ts-predicates

v0.6.2

Published

Useful type assertions for TS that happen both in typechecking and in runtime

Downloads

118

Readme

ts-predicates

A set of functions that ensure type safety both during typechecking AND during runtime.

Examples

lang=ts
const a = {} as Record<string, unknown>;
const b = { number: "2" } as Record<string, unknown>;
const c = { number: 2 } as Record<string, unknown>;

if (hasFieldOfType("number", predicates.number, a)) {
	a.number + 1;
	console.log("A has a number prop");
}else{
	a.number +1; // typescript error
}

if (hasFieldOfType("number", predicates.number, b)) {
	b.number + 1;
	console.log("B has a number prop");
}

if (hasFieldOfType("number", predicates.number, c)) {
	c.number + 1;
	console.log("C has a number prop");
}
console.log("utils finished");

You can test multiple fields at once:

lang=ts
const a = {};
if (
  !hasShape(
    <const>{
      string: predicates.string,
      undefined: predicates.undefined,
    },
    a
  )
) {
  throw new Error("wrong shape!");
}

You can infer object type from its shape:

lang=ts
const shape = {
	text: predicates.string,
	number: predicates.number,
} as const;

type the_shape = ShapeToType<typeof shape>

Dealing with nested/recursive types

In order to use recursive shapes/types, a little bit of syntax overhead is necessary.

Let's assume an example where we have a list of json objects. Some of them are images, and some of them are containers. Containers can contain other containers and images. For runtime type safety this would be enough:

lang=ts
const ImagePrimitiveShape = {
	type: predicates.const(<const>"image"),
	src: predicates.string,
};

type ImagePrimitiveType = ShapeToType<typeof ImagePrimitiveShape>;

type BlockPrimitiveType = {
	type: "block";
	content: Primitive[];
};

const BlockPrimitiveShape = <const>{
	type: predicates.const(<const>"block"),
	content: predicates.lazy(() =>
		predicates.array<Primitive>(
			predicates.or(
				predicates.shape(ImagePrimitiveShape),
				predicates.shape(BlockPrimitiveShape)
			)
		)
	),
};

type Primitive = ImagePrimitiveType | BlockPrimitiveType;

But, this would throw a compile error:

typescript [7022]: 'BlockPrimitiveShape' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.

In order to fix the compile error, we need to make the BlockPrimitiveShape const a little bit more verbose by manually specifying the type of the shape:

lang=ts
const BlockPrimitiveShape: {
	readonly type: ConstPredicate<"block">;
	readonly content: LazyPredicate<
		(BlockPrimitiveType | ImagePrimitiveType)[]
	>;
} = <const>{
	type: predicates.const(<const>"block"),
	content: predicates.lazy(() =>
		predicates.array<Primitive>(
			predicates.or(
				predicates.shape(ImagePrimitiveShape),
				predicates.shape(BlockPrimitiveShape)
			)
		)
	),
};

This results in a shapes+types combo than can check recursive types both at compile- and runtime:

lang=ts
if (hasShape(BlockPrimitiveShape, input)) {
	input.type; // "block"
	const element = input.content[0];
	element.type; // "image" | "block"
	if (element.type === "block") {
		element.content; // Primitive[]
		const nested_element = element.content[0];
		nested_element.type; // "block" | "image"
	}
}