marked icon indicating copy to clipboard operation
marked copied to clipboard

TypeScript and/or Documentation issue

Open sernaferna opened this issue 4 years ago • 3 comments

Marked version: 4.0.18 @types/marked version: 4.0.3

Describe the bug I've followed the documentation for creating a custom extension, but TypeScript complains about the lexer.inlineTokens() and parser.parseInline() methods. The sample extension in the documentation has one param for each, but TypeScript feels there should be two.

To Reproduce Here's a sample extension, that replaces ==highlighted text== with <mark>highlighted text</mark>:

import { marked } from 'marked';

export const highlightExtension: marked.TokenizerExtension | marked.RendererExtension = {
  name: 'highlightExtension',
  level: 'inline',
  start(src) {
    return src.match(/==/)?.index || -1;
  },
  tokenizer(src, tokens) {
    const rule = /^==([^=]+)==/;
    const match = rule.exec(src);
    if (!match) {
      return;
    }

    const token = {
      type: 'highlightExtension',
      raw: match[0],
      markText: match[1],
      tokens: [],
    };
    this.lexer.inline(token.markText, token.tokens);
    return token;
  },
  renderer(token) {
    // documentation has only one param for parseInline, too, but TS won't compile and I can't figure
    // out what the second should be
    return `<mark>${this.parser.parseInline(token.tokens)}</mark>`;
  },
};

Expected behavior I'm not sure if this is a problem with the documentation, with the @types/marked, or something else. For the life of me, however, I can't figure out what to use for the second parameter of the parseInline() method...

For now, I can skip the inline tokens / parse inline tokens for this particular extension, but for other extensions I want to write I'll definitely need to go a level deeper and parse the content of the text I'm passing through...

sernaferna avatar Aug 10 '22 20:08 sernaferna

The second parameter of parseInline() is a renderer. This is so we can pass in a text renderer for some calls.

For both of those calls the second parameter should be optional. This looks like an issue in @types/marked

UziTech avatar Aug 11 '22 05:08 UziTech

Aha! Confirmed! I hacked the types into my own code instead of importing from @types/marked and made the params optional, and it now works.

I'll submit a bit at DefinitelyTyped.

sernaferna avatar Aug 11 '22 14:08 sernaferna

Not that it matters, but I updated the code above to use lexer.inline instead of lexer.inlineTokens because of a huge performance boost; wouldn't want anyone to see the code above and do it the "slow" way. 🙂

sernaferna avatar Aug 11 '22 22:08 sernaferna