Typescript Type Error Mismatch

2/13/2025 12:00:00 AM

joe-jngigi

One of the good things and also a very frustrating thing about typescript is types, because oh my; once you start writing it, there is no going back.

In another day, I face a problem, which was basically a type error.


Type 'Record<string, unknown>' is missing the following properties from type 'T_FRONT_MATTER': title, date, authorts(2739)
types.ts(28, 3): The expected type comes from property 'frontmatter' which is declared here on type 'IntrinsicAttributes & T_COMPONENT_PROPS'
(property) frontmatter?: T_FRONT_MATTER | undefined

Why and What was the problem?

The data recieved had a type of Record<string, unknown>, but the data I expected to pass was of type T_FRONT_MATTER. We can say that the error is, fundamentally, a type mismatch, where we give a generic object, that is the type Record where we expected the type shown below.

type T_FRONT_MATTER = {
    [key: string]: string | undefined;
    title: string;
    date: string;
    author: string;
    topic?: string;
}

Fixing the Problem

The quickest fix is to “tell” TypeScript that the frontmatter data coming from compileMDX has the correct shape. In this case, I cast it when passing it to the component.

This assertion converts the generic Record<string, unknown> from compileMDX into your expected type (T_FRONT_MATTER), like shown below.

return (
  <Page
    frontmatter={data.frontmatter as T_FRONT_MATTER}
    title="Good Life"
  >
    {data.content}
    <footer>footer</footer>
  </Page>
);