add getNodeByType utility function and introduce type test

This commit is contained in:
syuilo 2021-03-29 10:11:44 +09:00 committed by marihachi
parent 7d303f2ced
commit abded7db7d
4 changed files with 42 additions and 1 deletions

View file

@ -3,14 +3,16 @@
"version": "0.11.0",
"description": "An MFM parser implementation with PEG.js",
"main": "./built/index.js",
"types": "./built/index.d.ts",
"scripts": {
"build": "npm run tsc && npm run peg",
"build-debug": "npm run tsc && npm run peg-debug",
"peg": "pegjs -o built/parser.js --allowed-start-rules fullParser,inlineParser,plainParser src/parser.pegjs",
"peg-debug": "pegjs -o built/parser.js --allowed-start-rules fullParser,inlineParser,plainParser --trace src/parser.pegjs",
"tsc": "tsc",
"tsd": "tsd",
"parse": "node ./built/cli/parse",
"test": "mocha -r ts-node/register 'test/**/*.ts'"
"test": "mocha -r ts-node/register 'test/**/*.ts' && npm run tsd"
},
"repository": {
"type": "git",
@ -25,6 +27,7 @@
"mocha": "8.3.x",
"pegjs": "0.10.x",
"ts-node": "9.1.x",
"tsd": "^0.14.0",
"typescript": "4.2.x"
},
"dependencies": {

View file

@ -56,6 +56,8 @@ export function extract(nodes: MfmNode[], type: (MfmNode['type'] | MfmNode['type
return dest;
}
export { getNodeByType } from './node';
export {
MfmNode,
MfmBlock,

View file

@ -157,3 +157,25 @@ export type MfmText = {
};
children?: [];
};
export type getNodeByType<T extends MfmNode['type']> =
T extends 'quote' ? MfmQuote :
T extends 'search' ? MfmSearch :
T extends 'blockCode' ? MfmCodeBlock :
T extends 'mathBlock' ? MfmMathBlock :
T extends 'center' ? MfmCenter :
T extends 'unicodeEmoji' ? MfmUnicodeEmoji :
T extends 'emojiCode' ? MfmEmojiCode :
T extends 'bold' ? MfmBold :
T extends 'small' ? MfmSmall :
T extends 'italic' ? MfmItalic :
T extends 'strike' ? MfmStrike :
T extends 'inlineCode' ? MfmInlineCode :
T extends 'mathInline' ? MfmMathInline :
T extends 'mention' ? MfmMention :
T extends 'hashtag' ? MfmHashtag :
T extends 'url' ? MfmUrl :
T extends 'link' ? MfmLink :
T extends 'fn' ? MfmFn :
T extends 'text' ? MfmText :
never;

14
test-d/index.ts Normal file
View file

@ -0,0 +1,14 @@
/**
* Unit testing TypeScript types.
* with https://github.com/SamVerschueren/tsd
*/
import { expectType } from 'tsd';
import { getNodeByType, MfmUrl } from '../built';
describe('#getNodeByType', () => {
it('returns node that has sprcified type', () => {
const x = null as unknown as getNodeByType<'url'>;
expectType<MfmUrl>(x);
})
});