Skip to content

Commit

Permalink
Type improvements (#12)
Browse files Browse the repository at this point in the history
  • Loading branch information
tommy-mitchell committed Mar 20, 2023
1 parent 3d3c62a commit 02dae42
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 7 deletions.
19 changes: 16 additions & 3 deletions index.d.ts
@@ -1,3 +1,16 @@
// Source: https://github.com/sindresorhus/type-fest/blob/main/source/internal.d.ts#L49
type Newline =
| '\u{A}' // '\n'
| '\u{D}' // '\r'
;

// Source: https://github.com/sindresorhus/type-fest/blob/main/source/trim.d.ts
type TrimStart<S extends string> = S extends `${Newline}${infer R}` ? TrimStart<R> : S;

type TrimEnd<S extends string> = S extends `${infer R}${Newline}` ? TrimEnd<R> : S;

export type Trim<S extends string> = TrimStart<TrimEnd<S>>;

/**
Trim from the start and end of a string.
Expand All @@ -9,7 +22,7 @@ trimNewlines('\n🦄\n🦄\r\n');
//=> '🦄\n🦄'
```
*/
export function trimNewlines(string: string): string;
export function trimNewlines<S extends string>(string: S): Trim<S>;

/**
Trim from the start of a string.
Expand All @@ -22,7 +35,7 @@ trimNewlines.start('\n🦄\r\n');
//=> '🦄\r\n'
```
*/
export function trimNewlinesStart(string: string): string;
export function trimNewlinesStart<S extends string>(string: S): TrimStart<S>;

/**
Trim from the end of a string.
Expand All @@ -35,4 +48,4 @@ trimNewlines.end('\n🦄\r\n');
//=> '\n🦄'
```
*/
export function trimNewlinesEnd(string: string): string;
export function trimNewlinesEnd<S extends string>(string: S): TrimEnd<S>;
20 changes: 16 additions & 4 deletions index.test-d.ts
@@ -1,6 +1,18 @@
import {expectType} from 'tsd';
import {expectType, expectAssignable} from 'tsd';
import {trimNewlines, trimNewlinesStart, trimNewlinesEnd} from './index.js';

expectType<string>(trimNewlines('\n🦄\r\n'));
expectType<string>(trimNewlinesStart('\n\n🦄\n'));
expectType<string>(trimNewlinesEnd('\n🦄\n\n'));
expectAssignable<string>(trimNewlines('\n🦄\r\n'));
expectAssignable<string>(trimNewlinesStart('\n\n🦄\n'));
expectAssignable<string>(trimNewlinesEnd('\n🦄\n\n'));

expectType<'🦄'>(trimNewlines('\n🦄\r\n'));
expectType<'🦄\n'>(trimNewlinesStart('\n\n🦄\n'));
expectType<'\n🦄'>(trimNewlinesEnd('\n🦄\n\n'));

expectType<' 🦄\n '>(trimNewlines('\n 🦄\n \n'));

declare const _string: string;

expectType<string>(trimNewlines(_string));
expectType<string>(trimNewlinesStart(_string));
expectType<string>(trimNewlinesEnd(_string));

0 comments on commit 02dae42

Please sign in to comment.