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:
- 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.)
- There are no
null
orundefined
(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:
- Mandatory properties (
BEGIN
,END
,VERSION
, andFN
) always do exist and are nevernull
orundefined
(aka “nullish”). - 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.)
- 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?
- Read the full documentation
- Browse the source code
- Integrate it into your application with NPM or Yarn. (We currently use it for CompanyON aka gutSTEIN and are thrilled.)
Enjoy the ride!