Skip to content

Instantly share code, notes, and snippets.

@temoncher
Created September 5, 2022 10:16
Show Gist options
  • Select an option

  • Save temoncher/d3c9b25b37f3e838dea1a3709188d567 to your computer and use it in GitHub Desktop.

Select an option

Save temoncher/d3c9b25b37f3e838dea1a3709188d567 to your computer and use it in GitHub Desktop.
`endsWith` typeguard
type EndsWithResult<S extends string, E extends string> = S extends `${string}${E}` ? S : `${S}${E}`
const endsWith = <E extends string>(end: E) => <S extends string>(str: S): str is EndsWithResult<S, E> => {
return str.slice(-end.length) === end;
}
const str = 'something' as `some${string}`;
const qqq = endsWith('foo')(str);
if (qqq) {
str;
} else {
str;
}
const strWithFoo = 'somefoo';
const qq = endsWith('foo')(strWithFoo);
if (qq) {
strWithFoo;
} else {
strWithFoo;
}
const strArr = ['some', 'somefoo', 'something'] as (`some${string}`)[];
const q = strArr.filter(endsWith('foo'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment