• 欢迎光临~

# Typescript类型体操 - Fill

## 题目

### 中文

`Fill`是 javascript 中常用的方法, 现在让我实现类型版本的 `Fill`
`Fill<T, N, Start?, End?>`, 正如你看到的那样, `Fill`接受四个泛型参数, 其中 `T``N` 是必填参数, `Start``End` 是可选参数

``````type exp = Fill<[1, 2, 3], 0>; // expected to be [0, 0, 0]
``````

### English

`Fill`, a common JavaScript function, now let us implement it with types.
`Fill<T, N, Start?, End?>`, as you can see,`Fill` accepts four types of parameters, of which `T` and `N` are required parameters, and `Start` and `End` are optional parameters.
The requirements for these parameters are: `T` must be a `tuple`, `N` can be any type of value, `Start` and `End` must be integers greater than or equal to 0.

``````type exp = Fill<[1, 2, 3], 0>; // expected to be [0, 0, 0]
``````

In order to simulate the real function, the test may contain some boundary conditions, I hope you can enjoy it 😃

## 答案

``````type Fill<
T extends unknown[],
N,
Start extends number = 0,
End extends number = T['length'],
Pending extends any[] = [],
Filled extends any[] = []
> = T extends [infer L, ...infer R]
? [
Pending['length'] extends Start
? Filled['length'] extends End
? L
: N
: L,
...Fill<
R,
N,
Start,
End,
Pending['length'] extends Start ? Pending : [...Pending, 0],
Filled['length'] extends End ? Filled : [0, ...Filled]
>
]
: [];
``````