0

I've got a component that uses these types and interfaces

import { FC } from 'react';

enum fieldTypes {
  Text = 'Text',
  DateTime = 'DateTime',
  Boolean = 'Boolean',
  Integer = 'Integer'
}

type Metadata = Record<string, { type: fieldTypes, widget?: string }>;

interface MetadataProperties {
    metaType: string;
    metadata: Array<Metadata>;
    dispatchSetProperty: (properties: any) => void;
}

const MetadataComponent: FC<MetadataProperties> = ({ metaType, metadata, dispatchSetProperty }) => {...}

When I try to do

   const metadata = [
    {
      description: {
        type: fieldTypes.Text
      },
    },
    {
      title: {
        type: fieldTypes.Text
      }
    }
   ];


<MetadataComponent metaType="language_metadata" metadata={metadata} dispatchSetProperty={dispatchSetProperty}/>

The last line is showing an error

TS2322: Type '({ description: { type: fieldTypes; }; title?: undefined; } | { title: { type: fieldTypes; }; description?: undefined; })[]' is not assignable to type 'Record<string, { type: fieldTypes; widget?: string | undefined; }>[]'.   Type '{ description: { type: fieldTypes; }; title?: undefined; } | { title: { type: fieldTypes; }; description?: undefined; }' is not assignable to type 'Record<string, { type: fieldTypes; widget?: string | undefined; }>'.     Type '{ description: { type: fieldTypes; }; title?: undefined; }' is not assignable to type 'Record<string, { type: fieldTypes; widget?: string | undefined; }>'.       Property 'title' is incompatible with index signature.         Type 'undefined' is not assignable to type '{ type: fieldTypes; widget?: string | undefined; }'.

I don't understand what's wrong. I've declared metadata as an Array of Metadata why is it erroring?

Any explanation would be awesome :)

steo
  • 4,586
  • 2
  • 33
  • 64
  • Did you try to explicitly define the type of the metadata declaration ? like `const metadata:Array` if you try this, do you get any linter error ? – jossefaz Apr 12 '21 at 17:00
  • Also I suggest this post : https://stackoverflow.com/questions/54100025/difference-between-index-signature-and-record-for-empty-object Does it helps you somehow ? – jossefaz Apr 12 '21 at 17:06
  • I tried jossefaz's suggestion to add the type annotation to the `metadata` variable and that seems to fix the error. The compiler infers the `metadata` array as something quite weird without the annotation, which makes sense as it has no way to know what it's supposed to be. The type it infers is `{ description: { type: fieldTypes; }; title?: undefined; } | { title: { type: fieldTypes; }; description?: undefined; })[]` which is the union of the two elements in the array – cdimitroulas Apr 12 '21 at 22:21

0 Answers0