Home > database >  Type { id: 'string } is missing the following properties
Type { id: 'string } is missing the following properties

Time:07-19

I'm learning TS and I'm trying to add some TS to a NextJS project. I've used this example and I've tried to add the following type for allPostsData, but TS says that date and title are missing. Both are variables fetched from a MD file with gray-matter.

import fs from "fs";
import path from "path";
import matter from "gray-matter";

const postsDirectory = path.join(process.cwd(), "posts");

export function getSortedPostsData() {
  // Get file names under /posts
  const fileNames = fs.readdirSync(postsDirectory);
  const allPostsData: { id: string; date: string; title: string }[] =
    fileNames.map((fileName) => {
      // Remove ".md" from file name to get id
      const id = fileName.replace(/\.md$/, "");

      // Read markdown file as string
      const fullPath = path.join(postsDirectory, fileName);
      const fileContents = fs.readFileSync(fullPath, "utf8");

      // Use gray-matter to parse the post metadata section
      const matterResult = matter(fileContents);

      // Combine the data with the id
      return {
        id,
        ...matterResult.data,
      };
    });
  // Sort posts by date
  return allPostsData.sort((a, b) => {
    if (a.date < b.date) {
      return 1;
    } else {
      return -1;
    }
  });
}

CodePudding user response:

Typescript does not know that your markdown file contains a date and a title. You can fix this by explicitly specifying the type that matter(fileContents) returns.

const matterResult = matter(fileContents) as {date: string, title: string};

  • Related