vcard4-ts: A TypeScript-first vCard parser

vCard4-ts business card

TypeScript is the amiable and helpful sibling of JavaScript, always there for you, whether you currently do want type safety or you don’t. So it was only natural to use it to make handling digital business cards easier. vCard4-ts is the result of this attempt.

Design goals

vcard4-ts, an open source project available from GitLab or GitHub, was designed with the following goals:

  • RFC 6350 (the vCard version 4 specification) compliant
  • TypeScript (and type safety) from the ground up
  • Don’t Repeat Yourself to avoid mistakes: The data structure definition for the caller was created from RFC 6350 and also contains the necessary instructions for the parser itself
  • The returned data structure is easy to use: As few run-time decisions as possible to access the data faster and safer

Principles in action

Here is a minimal piece of code, but enough for explaining some basic principles:

import { parseVCards } from 'vcard4-ts';
import { readFileSync } from 'fs';

const vcf = readFileSync('example.vcf').toString();

const cards = parseVCards(vcf);
if (cards.vCards) {
  for (const card of cards.vCards) {
    console.log('Card found for ' + card.FN[0].value[0]);
  }
} else {
  console.error('No valid vCards in file');
}

We can see two basic principles in action:

  1. The types are always clear, no expensive run-time testing whether there is just a single value or there are multiple values. (This is the prime directive.)
  2. There are no null or undefined (aka nullish) values; and any arrays will always have at least one element. This is the secondary directive.

As a result of these principles, the following rules apply:

  1. Mandatory properties (BEGIN, END, VERSION, and FN) always do exist and are never null or undefined (aka “nullish”).
  2. Optional properties (all the others defined in RFC 6350) only exist, if they do appear in the file. I.e., if they exist, they also have a value and are never nullish. (However, the strings may still be empty.)
  3. To match the prime directive, any property, whether mandatory or optional, that may appear more than once, is always an array of values. I.e., unlike most other parsers, there is no need to check the number of values at runtime. This is what type safety was meant to be, no?

These rules make software development more predictable and thus faster, less error-prone:

  • Typescript can verify type correctness.
  • Autocompletion and type inference in development environments such as VSCode/VSCodium works and is very helpful.

Ready for a spin?

Enjoy the ride!

Let’s stay in touch!

Receive a mail whenever I publish a new post.

About 1-2 Mails per month, no Spam.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Web apps