Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type improvements #12

Merged
merged 2 commits into from
Mar 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
19 changes: 16 additions & 3 deletions index.d.ts
Original file line number Diff line number Diff line change
@@ -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🦄\r\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
Original file line number Diff line number Diff line change
@@ -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));