Created
May 13, 2025 16:50
-
-
Save nikoheikkila/2516e89307782c092274ff5171af063c to your computer and use it in GitHub Desktop.
TypeScript type-system validation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type IPv4Tuple = [number, number, number, number]; | |
type IPv4String = `${number}.${number}.${number}.${number}`; | |
/** | |
* TypeScript validates up to a point. | |
* But we still need runtime validation and a type guard. | |
**/ | |
const createIpAddress = (values: number[]): IPv4String => { | |
if (!isValidIpAddress(values)) { | |
throw new Error(`Invalid IP address: ${values.join('.')}`); | |
} | |
// Type safety is guaranteed while unpacking the tuple | |
const [first, second, third, fourth] = values; | |
// We cannot use `Array.prototype.join()` because `string` does not satisfy `IPv4String` | |
return `${first}.${second}.${third}.${fourth}`; | |
} | |
const isValidIpAddress = (list: number[]): list is IPv4Tuple => | |
list.length === 4 | |
&& list.every(isInteger) | |
&& list.every((value) => isInRange(value, 0, 255)); | |
const isInteger = (value: number): boolean => | |
Math.floor(value) === value; | |
const isInRange = (value: number, min: number, max: number): boolean => | |
value >= min && value <= max; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment