Advanced TypeScript #5: Simulating tuples
Here’s part 5 of 7 of the Advanced TypeScript series, where I share TypeScript patterns I’ve encountered in enterprise grade applications.
5. Simulating tuples
In TypeScript, you can define arrays of explicit lengths using bracket notation, eg. type MyPair = [number, string]
.
This can be useful to simulate tuples using an enum with 2 values.
enum DoorState {
OPEN = 'OPEN',
CLOSED = 'CLOSED',
}
function getInverseValue<T>(val: T, possibleVals: [T, T]): T {
return possibleVals[0] === val ? possibleVals[1] : possibleVals[0];
}
import assert from 'node:assert';
import test from 'node:test';
test('inverts the enum value', () => {
assert.equal(
getInverseValue<DoorState>(DoorState.OPEN, [
DoorState.OPEN,
DoorState.CLOSED,
]),
DoorState.CLOSED
);
assert.equal(
getInverseValue<DoorState>(DoorState.CLOSED, [
DoorState.OPEN,
DoorState.CLOSED,
]),
DoorState.OPEN
);
});
That's this week's pattern, you can get a sneak peek of the rest at codewithhugo.com/typescript-types-in-the-trenches/, or access the annotated source at github.com/HugoDF/real-world-ts.
Don't miss what's next. Subscribe to Deep in Software with Hugo: