Created
September 5, 2022 10:16
-
-
Save temoncher/d3c9b25b37f3e838dea1a3709188d567 to your computer and use it in GitHub Desktop.
`endsWith` typeguard
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 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