Skip to content

Conversation

@sillvva
Copy link
Contributor

@sillvva sillvva commented May 5, 2024

This PR fixes a couple of issues, which can be easily explained with this playground.

Issue Summary

By extending object you are extending all types of objects (including classes with methods and properties). Instead you should extend this type:

type DictOrArray = Record<PropertyKey, unknown> | unknown[];

This type only extends basic objects and arrays. No classes or branded types. An added benefit of this is that you no longer need to check built-in class types (ex. Date, Blob, etc). This tweak automatically handles all of those types correctly.

Detailed Examples of Issues

The playground linked above showcases this as well.

import { ExampleData, Id } from "./example";

/**
 * Example 1: Paths from Class Methods/Properties
 */
import { FormPath } from "sveltekit-superforms";
import { FormPath as FixedFormPath } from "./fixed";

// When you use the built-in FormPath helper, it adds a path for every class property/method.
// This is undesirable. Instead, it should only provide paths for basic objects and arrays.

type BadFormPath = FormPath<ExampleData>;
// type BadFormPath = "id" | "message" | "date" | "user" | "tags" | "id.charAt" | "id.charCodeAt" | "id.concat"
//   | "id.indexOf" | "id.lastIndexOf" | "id.localeCompare" | "id.match" | "id.replace" | ... 74 more ...
//   | `tags[${number}]`

type GoodFormPath = FixedFormPath<ExampleData>;
// type GoodFormPath = "id" | "message" | "date" | "user" | "tags" | "user.id" | "user.name" | `tags[${number}]`

/**
 * Example 2: Incompatible with Branded Types
 */
import { FormPathLeaves } from "sveltekit-superforms";
import { FormPathLeaves as FixedFormPathLeaves } from "./fixed";

// When using branded types, the helpers are unable to get the exact path, because branded types
// are both primitive and objects. You can even use the branded type to filter it.

type BadLeaves = FormPathLeaves<ExampleData>;
// type BadLeaves = "message" | "date" | "id.length" | "user.id.length" | "user.name" | `tags[${number}]`

type GoodLeaves = FixedFormPathLeaves<ExampleData>;
// type GoodLeaves = "id" | "message" | "date" | "user.id" | "user.name" | `tags[${number}]`

type IdLeaves = FixedFormPathLeaves<ExampleData, Id>;
// type IdLeaves = "id" | "user.id"

@vercel
Copy link

vercel bot commented May 5, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
superforms ✅ Ready (Inspect) Visit Preview 💬 Add feedback May 5, 2024 0:46am

@ciscoheat
Copy link
Owner

Thank you, very useful!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants