UNPKG

947 BTypeScriptView Raw
1import type {IsNegative} from './numeric';
2import type {Subtract} from './subtract';
3
4/**
5Returns a new string which contains the specified number of copies of a given string, just like `String#repeat()`.
6
7@example
8```
9import {StringRepeat} from 'type-fest';
10
11declare function stringRepeat<
12 Input extends string,
13 Count extends number
14>(input: Input, count: Count): StringRepeat<Input, Count>;
15
16// The return type is the exact string literal, not just `string`.
17
18stringRepeat('foo', 2);
19//=> 'foofoo'
20
21stringRepeat('=', 3);
22//=> '==='
23```
24
25@category String
26@category Template literal
27*/
28export type StringRepeat<
29 Input extends string,
30 Count extends number,
31> = number extends Count
32 ? Input extends ''
33 ? ''
34 : string
35 : IsNegative<Count> extends true
36 ? never
37 : Count extends 0
38 ? ''
39 : string extends Input
40 ? string
41 : StringRepeat<Input, Subtract<Count, 1>> extends infer R extends string
42 ? `${Input}${R}`
43 : never;