Conditionally prepend a string to another string in TypeScript

Thomas Rubattel
2 min readDec 16, 2022

--

Credits: John Barkiple on Unsplash

This short article will discuss on how to prepend a string conditionally in the most composable way.

Use case

The goal to achieve is to prepend a string — a separator— to another string conditionally.

A code snippet speaks a thousand words. The property deathDate has to be prepended by a / but potentially does not exist — means with value null— hence the condition.

type Person = {
birthDate: string;
deathDate: string | null;
};

const people: Array<Person> = [
{
birthDate: '1958-05-30',
deathDate: '2019-12-09'
},
{
birthDate: '2010-07-22',
deathDate: null,
}
];

// Out of the data structure above, we need the following:
// ["1958-05-30 / 2019-12-09", "2010-07-22"]

padStart

One way of achieving the solution is to use padStart method on String.

type Person = {
birthDate: string;
deathDate: string | null;
};

const people: Array<Person> = [
{
birthDate: '1958-05-30',
deathDate: '2019-12-09'
},
{
birthDate: '2010-07-22',
deathDate: null,
}
];

const lifePeriods = people.map((person) =>
person.birthDate.concat(
person.deathDate?.padStart(person.deathDate.length + 3, " / ") || ''
)
);

// ["1958-05-30 / 2019-12-09", "2010-07-22"]

join

Another way of achieving the solution is to use join method on Array.

type Person = {
birthDate: string;
deathDate: string | null;
};

const people: Array<Person> = [
{
birthDate: '1958-05-30',
deathDate: '2019-12-09'
},
{
birthDate: '2010-07-22',
deathDate: null,
}
];

const lifePeriods = people.map((person) =>
[person.birthDate, person.deathDate]
.filter(Boolean)
.join(" / ")
);

// ["1958-05-30 / 2019-12-09", "2010-07-22"]

Takeaway

The solution consisting of putting the two strings into an array, removing the last element in case that one is null and finally combining the both with a separator does compose better.

In functional programming style, function composition and function decoration play a key role since functions are the building blocs of this paradigm.

--

--