Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow type of "data" property to be set using generic type #135

Open
FunctionDJ opened this issue Jan 22, 2022 · 3 comments
Open

Allow type of "data" property to be set using generic type #135

FunctionDJ opened this issue Jan 22, 2022 · 3 comments

Comments

@FunctionDJ
Copy link

FunctionDJ commented Jan 22, 2022

Right now there is no way to set the type of file.data except with as.
In general, as in TypeScript conveys incomplete typings for external libraries or insufficient time to fix an issue with types.
You want to reduce as in a code base as much as possible in order for it to be a red flag when it comes up.
However, with I/O we tap outside of types and telling our code which shape a resulting object will have is necessary.
Other libraries achieve this by simply exposing a generic type param on classes or methods like this:

interface MyFrontMatter {
  title: string
  date: string
}

const { data } = matter<string, {}, MyFrontMatter>(fileContents);
const { title, date } = data; // statically typed, TS knows that title is a string, not 'any'

The advantage is that this conveys intent, that the typings are as clean as they can be.
It would be great if you could add this as a third param to the types!

declare function matter<
  I extends matter.Input,
  O extends matter.GrayMatterOption<I, O>,
  MatterShape extends Record<string, unknown> // not sure about this
>(input: I | { content: I }, options?: O): matter.GrayMatterFile<I, MatterShape>

// ...

  interface GrayMatterFile<I extends Input, MatterShape extends Record<string, unknown>> {
    data: MatterShape
    content: string
    excerpt?: string
    orig: Buffer | I
    language: string
    matter: string
    stringify(lang: string): string
  }```
@rocktimsaikia
Copy link

rocktimsaikia commented Mar 4, 2022

++
Yes. This would be quite helpful.

FunctionDJ added a commit to FunctionDJ/gray-matter that referenced this issue Mar 6, 2022
@gd-cho
Copy link

gd-cho commented Apr 5, 2022

yse, I have this, It kind of bothers me

@HiDeoo
Copy link

HiDeoo commented Jan 5, 2023

As I've encountered this limitation multiple times, I created a small wrapper for gray-matter using zod to actually validate front matter and get proper type inference, e.g.:

import { parse } from 'zod-matter'
import { z } from 'zod'

const { data } = parse('---\nauthor: HiDeoo\n---\n# Hello world!', z.object({ author: z.string() }))
//       ^? { author: string }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants