• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15/**---
16 description: >
17   The following type won't be optimized, since it uses the result of a conditional type by adding it to a union.
18   You can introduce a helper that takes an "accumulator" type parameter to make it tail-recursive
19 module: ESNext
20 isCurrent: true
21---*/
22
23
24import { Assert } from "../../../suite/assert.js"
25
26type RunObtain<S> = S extends `${infer Char}${infer Rest}`
27    ? Char | RunObtain<Rest>
28    : never;
29type gc = RunObtain<"                getChar">;
30var g1: gc = "e";
31Assert.isString(g1);
32
33type RunObtain1<S> = RunObtainHelper<S, never>;
34type RunObtainHelper<S, Acc> = S extends `${infer Char}${infer Rest}`
35    ? RunObtainHelper<Rest, Char | Acc>
36    : Acc;
37
38type gch = RunObtainHelper<string, number>;
39var g2: gch = 10;
40Assert.isNumber(g2);
41
42let g3: RunObtain1<'    NEW'> = ' ';
43Assert.equal(g3, ' ');
44g3 = 'E';
45Assert.equal(g3, 'E');
46
47let g4: RunObtainHelper<'  NARC  ', 'ACC'> = 'ACC';
48Assert.equal(g4, 'ACC');
49g4 = 'N';
50Assert.equal(g4, 'N');