Hello!
Today I found myself in a situation where I had to remove the numbers at the end of each string of one union type.
This is because I have my color tokens defined as an union of grey1 | grey2 | greyNN | red1 | red2 | redNN
and I wanted just the name part for a function that was going to compose them, something like this:
function doSomething (color: string) {
return { bg: `${color}1`, text: `${color}11` }
}
And I wanted to make sure that I only passed valid colors. But for that I need the list without the number at the end.
I was surprised of how easy was to encode this using type-fest:
import { Split } from 'type-fest';
type Digit = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9';
type NumberAtEnd = `${string}${Digit}`;
export type RemoveNumbers<S extends string> = S extends `${NumberAtEnd}${Digit}`
? RemoveNumbers<Split<S, Digit>[0]>
: Split<S, Digit>[0];
What do you think about adding this utility to the library? It can easily be extended to do a maximum of N digits. To be honest, I don't think anyone will need anything more than 2 or 3 or else you are doing something probably wrong
Regards
Pay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too