diff --git a/index.d.ts b/index.d.ts index cdce30faf..ca4c0ac09 100644 --- a/index.d.ts +++ b/index.d.ts @@ -155,6 +155,7 @@ export type {Join} from './source/join'; export type {Split} from './source/split'; export type {Trim} from './source/trim'; export type {Replace} from './source/replace'; +export type {StringRepeat} from './source/string-repeat'; export type {Includes} from './source/includes'; export type {Get} from './source/get'; export type {LastArrayElement} from './source/last-array-element'; diff --git a/readme.md b/readme.md index 48a9d7065..965511cc4 100644 --- a/readme.md +++ b/readme.md @@ -269,6 +269,7 @@ type ShouldBeNever = IfAny<'not any', 'not never', 'never'>; - [`Split`](source/split.d.ts) - Represents an array of strings split using a given character or character set. - [`Replace`](source/replace.d.ts) - Represents a string with some or all matches replaced by a replacement. - [`StringSlice`](source/string-slice.d.ts) - Returns a string slice of a given range, just like `String#slice()`. +- [`StringRepeat`](source/string-repeat.d.ts) - Returns a new string which contains the specified number of copies of a given string, just like `String#repeat()`. ### Array diff --git a/source/string-repeat.d.ts b/source/string-repeat.d.ts new file mode 100644 index 000000000..b03581b81 --- /dev/null +++ b/source/string-repeat.d.ts @@ -0,0 +1,43 @@ +import type {IsNegative} from './numeric'; +import type {Subtract} from './subtract'; + +/** +Returns a new string which contains the specified number of copies of a given string, just like `String#repeat()`. + +@example +``` +import {StringRepeat} from 'type-fest'; + +declare function stringRepeat< + Input extends string, + Count extends number +>(input: Input, count: Count): StringRepeat; + +// The return type is the exact string literal, not just `string`. + +stringRepeat('foo', 2); +//=> 'foofoo' + +stringRepeat('=', 3); +//=> '===' +``` + +@category String +@category Template literal +*/ +export type StringRepeat< + Input extends string, + Count extends number, +> = number extends Count + ? Input extends '' + ? '' + : string + : IsNegative extends true + ? never + : Count extends 0 + ? '' + : string extends Input + ? string + : StringRepeat> extends infer R extends string + ? `${Input}${R}` + : never; diff --git a/test-d/string-repeat.ts b/test-d/string-repeat.ts new file mode 100644 index 000000000..ef5538efc --- /dev/null +++ b/test-d/string-repeat.ts @@ -0,0 +1,19 @@ +import {expectType} from 'tsd'; +import type {StringRepeat} from '../index'; + +declare const unknown: unknown; + +expectType>(''); +expectType>(unknown as never); +expectType>(''); +expectType>(unknown as never); +expectType>(''); +expectType>(unknown as string); +expectType>(unknown as string); +expectType>(unknown as never); +expectType>(''); +expectType>('0'); +expectType>('00000'); +expectType>(''); +expectType>('012345-'); +expectType>('012345-012345-012345-012345-012345-');