measuredco / puck

The visual editor for React
https://puckeditor.com
MIT License
5.01k stars 273 forks source link

Type error when trying to conditionally show fields using resolveFields #530

Open the-code-raccoon opened 1 month ago

the-code-raccoon commented 1 month ago

Background

Puck version: 0.15.0

Current Behaviour

I have a component where I would like to show field A conditionally based on the value of field B. I created a type for the component as follows:

type MyComponentProps {
    fieldA?: string;
    fieldB: boolean;
}

My component looks like this:

const MyComponent = (): ComponentConfig<MyComponentProps> => {
     ... ,
     resolveFields: (data, { fields }) => {
          if (data.props.fieldB) {
               return { ... fields, fieldA: undefined } 
          }
          return fields
     }
}

But then I receive the following type error on resolveFields: Types of property 'fieldA' are incompatible. Type 'undefined' is not assignable to type 'Field<string | undefined>'

Note field A does renders conditionally as desired even with the type error.

Expected Behaviour

I would assume this method of showing fields conditionally wouldn't result in any type errors considering I found this method for conditionally showing fields in the puck editor demo.

Workaround

For now I've just put @ts-ignore above resolveFields. Please let me know if there is another way of conditionally showing fields or if I did something incorrect in my implementation, thanks!

chrisvxd commented 1 month ago

Good catch @the-code-raccoon! This is is an issue with how the types for component fields are defined. It's assumed that every prop is required as a field, regardless of whether or not the prop is optional. This was okay before we had conditional fields, because it wouldn't have made sense to include a prop without a field, but doesn't make sense with dynamic fields.

I'll mark this as a bug.