jhermsmeier / node-vcf

A not so forgiving vCard / vcf parser
MIT License
107 stars 35 forks source link

Make "vCard.get" Generic #46

Open peter-mghendi opened 2 years ago

peter-mghendi commented 2 years ago

Hi :wave:,

I'm using this excellent library with typescript, and I have a request regarding the type definitions. Currently fetching a value looks like this:

// Must assert the type, since get returns string | object. 
const photo: string = <string>card.get('photo').valueOf();

It starts looking funny when you need to perform more actions on the value:

const categories = (<string>card.get('photo').valueOf()).split(',');

I propose that Property be generic, maybe still constrain it to just strings and objects with <Type extends string | object> so that I'm able to do:

const categories = card.get<string>('photo').valueOf().split(',');

The above would also make it possibe to type-hint against specific interfaces.

I'm willing to submit a pull request for this.

EDIT:

Also having this for Property | Property[] would be useful, so maybe something like:

const categories = card.get<Property<string>[]>('photo').valueOf().split(',');

EDIT 2:

Even better, it would be nice if get could return a single type (e.g just Property[]) so that we do not have to check if the returned value is a string or an array.

jhermsmeier commented 2 years ago

Hey :) That is totally something we could do here

I'm willing to submit a pull request for this.

That'd be great!

Even better, it would be nice if get could return a single type (e.g just Property[]) so that we do not have to check if the returned value is a string or an array.

Indeed, having a single generic return type would be nice. I've been planning to steamroll this module for some time and make a v3 from scratch, because the approach I took initially with internal structure and return values etc. isn't terribly great. But as things go, one has less and less time, and it never happens 😅

peter-mghendi commented 2 years ago

Awesome! I'll try and cobble up something and submit it for review soon.