diff --git a/index.d.ts b/index.d.ts index ec82718..e152d7c 100644 --- a/index.d.ts +++ b/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 `${Newline}${infer R}` ? TrimStart : S; + +type TrimEnd = S extends `${infer R}${Newline}` ? TrimEnd : S; + +export type Trim = TrimStart>; + /** Trim from the start and end of a string. @@ -9,7 +22,7 @@ trimNewlines('\nšŸ¦„\nšŸ¦„\r\n'); //=> 'šŸ¦„\nšŸ¦„' ``` */ -export function trimNewlines(string: string): string; +export function trimNewlines(string: S): Trim; /** Trim from the start of a string. @@ -22,7 +35,7 @@ trimNewlines.start('\nšŸ¦„\r\n'); //=> 'šŸ¦„\r\n' ``` */ -export function trimNewlinesStart(string: string): string; +export function trimNewlinesStart(string: S): TrimStart; /** Trim from the end of a string. @@ -35,4 +48,4 @@ trimNewlines.end('\nšŸ¦„\r\n'); //=> '\nšŸ¦„' ``` */ -export function trimNewlinesEnd(string: string): string; +export function trimNewlinesEnd(string: S): TrimEnd; diff --git a/index.test-d.ts b/index.test-d.ts index 49b07a1..88b6d39 100644 --- a/index.test-d.ts +++ b/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(trimNewlines('\nšŸ¦„\r\n')); -expectType(trimNewlinesStart('\n\nšŸ¦„\n')); -expectType(trimNewlinesEnd('\nšŸ¦„\n\n')); +expectAssignable(trimNewlines('\nšŸ¦„\r\n')); +expectAssignable(trimNewlinesStart('\n\nšŸ¦„\n')); +expectAssignable(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(trimNewlines(_string)); +expectType(trimNewlinesStart(_string)); +expectType(trimNewlinesEnd(_string));