Skip to content

v2.4.0 - Type guards 🛡️

Latest

Choose a tag to compare

@gustavoguichard gustavoguichard released this 30 Oct 13:58
v2.4.0
4af2277

What's Changed

This release introduces type guards: includesGuard, startsWithGuard, and endsWithGuard. Instead of returning a strongly-typed boolean, they narrow the input string to the members of a string-literal union that satisfy the check, in both branches of the condition:

import { includesGuard } from 'string-ts'

declare const reportType:
  | 'HouseCalendar'
  | 'SenateCalendar'
  | 'HouseFirstReading'

if (includesGuard(reportType, 'Calendar')) {
  reportType
  //  ^ 'HouseCalendar' | 'SenateCalendar'
} else {
  reportType
  //  ^ 'HouseFirstReading'
}

The filters behind them are exported too, as WhenIncludes, WhenStartsWith, and WhenEndsWith:

St.WhenIncludes<'abcde' | 'xyz', 'bcd'> // 'abcde'
St.WhenStartsWith<'abc' | 'xyz', 'a'> // 'abc'
St.WhenEndsWith<'abc' | 'xyz', 'c'> // 'abc'

This is purely additive. A TypeScript type predicate always surfaces a plain boolean to the caller, so includes, startsWith, and endsWith keep their literal true/false return. Reach for the plain function when you want the literal boolean, and for the *Guard function when you want narrowing.

Bug Fixes

  • fix: cap Repeat type at 45 to prevent TS2589 depth error (#294)
    • Counts above 45 now fall back to string instead of failing with TS2589
    • padStart and padEnd inherit the fix, falling back to a template literal such as `${string}hello`

Documentation

  • Added a Known limitations section to the README, covering ASCII-only support and the recursion-depth threshold

PRs

Full Changelog: v2.3.1...v2.4.0