Array for string literals
Array of string literals for the runtime.
If you code in typescript, you probably don't need any of this.
Overview
The StringList class extends the Array with new methods and supercharges the array interface to infer the string literals.
-
Methods that mutate the array in place like push, pop, shift, unshift, splice should not be used, there is a strict export that enforce this restriction.
-
no changes is made to the execution of the methods to minimize side effects and the interface is compatible with the native array to work with library expecting arrays.
-
an arr.enum
property is available to access the literals similar to the way an enum is accessed in typescript.
-
then additional methods for string literals and type constructs are implemented:
without(...$)
: filter out the given values, accept string and StringList.withPrefix($)
and withSuffix($)
: add prefix/suffix to all the words.value($)
: similar to enum but throws an error if the value doesn't exists.enum[$]:$
Object is exposed as readonly.withTrim()
: trim all the words.withReplace(search, replacement)
: call the String.prototype.replace on all.withReplaceAll(search, replacement)
: call the String.prototype.replaceAll on all.to"Case"()
methods for case transform, uppercase, lowercase capitalize, etc...toRecordValue/toRecordType
methods to create a type of Record<literal, type | typeof value>
with initial value and builtin or infered types.
The array order is preserved in a Tuple to infer the types when possible, some methods like toSorted will cause the new instance to be flagged as unsorted and methods like join() will return a generic string type.
Installation
npm install --save string-literal-list
yarn add string-literal-list
Code
import { stringList } from 'string-literal-list';
import { sl } from 'string-literal-list';
let v = sl('foo', 'bar');
v.enum.foo;
v.includes(any);
v.withPrefix('prefix.');
v.withSuffix('.suffix');
v.concat('zing', 'boom');
v.concatList(sl('zig', 'zag'));
v.value('foo') => 'foo';
v.value('not') => throws;
v.enum['not'] => undefined;
v.withTrim()
v.withReplace('a', 'e')
v.withReplaceAll('o', 'e')
v.without('foo')
import { sl } from 'string-literal-list';
const list = sl('foo', 'bar');
list.enum;
const prefixed = list.withPrefix('prefix.');
const suffixed = list.withSuffix('.suffix');
const concat = list.concat('bar', 'foo');
const concatList = prefixed.concatList(suffixed);
concatList.join('::');
const without = concatList.without('prefix.foo', 'bar.suffix');
const withoutList = concatList.without(sl('prefix.foo', 'bar.suffix'));
const bothWay = list.withPrefix('data.').withSuffix('.ext');
let val;
list.includes(val);
const arr = list.mutable();
list.value('foo');
list.value('n');
const scored = sl(' has ', 'spaces', ' between ', ' o r', 'in the words')
.withTrim()
.withReplaceAll(' ', '_');
const Upper = sl('foo', 'bar').toUpperCase();
list.concat(...(string)[]) and list.concatList(sl)
list.concat()
accept only string as arguments to enable inference.
If a native array is passed the string literals won't be inferred.
list.concatList()
accept 1 list of string literals.
sl('foo', 'bar').concat('zing', 'foo').concatList(sl('gurgle', 'doink'));
list.concat(['boom', 'bar']);
filter / map / reduce and other array methods
The results of those methods will result in type loose string[]
or returned U[]
for map / reduce.
References
See ./types.d.ts and ./StringLiteralList.d.ts for more info on the methods which methods are available and specific type overrides.
Why?
The javascript Array interface is not designed to work with constant string literal.
The methods like concat, or includes will expect only the constants as argument, which makes a method like includes() useless, and others build method annoying to type when constructing the constants.
workarounds
- includes(): using mapped object in your code instead of the array, e.g.
!!MY_LIST_AS_unnecessary_MAP[val]
, but if you want type safety this means no .concat(), no .includes(), no iteration without creating new variables. - concat(): just concatenate your workarounds into a single type. e.g.
/** @type {((keyof typeof MAP_A) | MAPPED_FROM_MAP_B)[]} */
not solving any issues with the underlying unusable array methods.
Code showing the problem using typed array
const arr = ['foo', 'bar'];
arr.push('d');
arr.includes('zing');
arr.concat(['zing']);
const O = {
foo: 'foo',
bar: 'bar',
};
const lit = Object.keys(O);
const lit = new Array('foo', 'bar');
lit.includes('asd');
let val = 'asd';
lit.includes(val);
lit.concat([val]);
lit.concat(val);
Credits
Thanks to @gustavoguichard and his work on https://github.com/gustavoguichard/string-ts that taught me how to work with string literals.