dittowords/ditto-react

type safety question

dgreene1 opened this issue · 3 comments

Does this library contain any type safety such that the compilation step would confirm that the componentId prop corresponds with text that is actually stored in

So for example, if we have the following React code:

const MyPage => () => {
 return (
   <div>
     <h1><Ditto componentId="home.title" /></h2>
     lorem ipsum
   </div>
 );
}

And then let's assume that the source JSON doesn't have a "home.title" entry.

In that scenario will the compiler fail saying that componentId doesn't exist?

I've made a TypeScript Playground example demonstrating how this is possible with string literal unions. Here is an image of the error message I would hope to see:

image

Hey @dgreene1, thanks for opening!

This level of type safety is not currently available out of the box (componentId and similar props are internally typed as string), but it's on our roadmap for the near future; I don't have a concrete timeline yet, but I will let you know when it's out!

Although it's not as convenient, in the interim you can achieve the type safety you're looking for by wrapping the <Ditto /> component in a simple abstraction that is type safe. I created this code sandbox as an example: https://codesandbox.io/s/late-pond-qmc1gb?file=/src/App.tsx

Here is a relevant code snippet for anyone skimming:

import { ComponentProps } from "react";
import { DittoComponent } from "ditto-react";

import dittoJson from "./ditto/ditto-component-library.json";

// will need to change this according to how you're exporting your data from Ditto
type ComponentId = keyof typeof dittoJson;

type DittoComponentProps = ComponentProps<typeof DittoComponent>;
type DittoComponentPropsWithoutComponentId = Omit<
  DittoComponentProps,
  "componentId"
>;

type TextProps = DittoComponentPropsWithoutComponentId & {
  componentId: ComponentId;
};

export const TextComponent = (props: TextProps) => (
  <DittoComponent {...props} />
);
// Error: invalid type ❌
<TextComponent componentId="key-not-in-your-data" />

// Ok ✔️
<TextComponent componentId="key-in-your-data" />

Thank you for the stopgap solution. I think it would be valuable to automatically build this type out in the same way that Prisma builds it’s automatically updating ORM.

We still hope to eventually add this level of type safety out of the box (likely by generating typings as part of running CLI commands), but I'm going to close this for now since there is an interim solution that works. Thanks again for opening!