Skip to content

Commit e044bd1

Browse files
BendingBendersindresorhus
authored andcommitted
TypeScript - Fix handling of union types (#11)
Fixes #8 Fixes #10
1 parent f789ce5 commit e044bd1

File tree

2 files changed

+30
-9
lines changed

2 files changed

+30
-9
lines changed

index.d.ts

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -23,12 +23,16 @@ arrify(undefined);
2323
//=> []
2424
```
2525
*/
26-
declare function arrify(value: null | undefined): [];
27-
declare function arrify(value: string): [string];
28-
declare function arrify<ValueType>(value: ValueType[]): ValueType[];
29-
// TODO: Use 'readonly ValueType[]' in the next major version
30-
declare function arrify<ValueType>(value: ReadonlyArray<ValueType>): ReadonlyArray<ValueType>;
31-
declare function arrify<ValueType>(value: Iterable<ValueType>): ValueType[];
32-
declare function arrify<ValueType>(value: ValueType): [ValueType];
26+
declare function arrify<ValueType>(
27+
value: ValueType
28+
): ValueType extends (null | undefined)
29+
? []
30+
: ValueType extends string
31+
? [string]
32+
: ValueType extends ReadonlyArray<unknown> // TODO: Use 'readonly unknown[]' in the next major version
33+
? ValueType
34+
: ValueType extends Iterable<infer T>
35+
? T[]
36+
: [ValueType];
3337

3438
export = arrify;

index.test-d.ts

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,25 @@ expectType<string[]>(arrify(['🦄']));
88
expectType<[boolean]>(arrify(true));
99
expectType<[number]>(arrify(1));
1010
expectType<[{}]>(arrify({}));
11-
expectType<([string | number, string | number])[]>(
12-
arrify(new Map<string | number, string | number>([[1, 2], ['a', 'b']]))
11+
expectType<[number, string]>(arrify([1, 'foo']));
12+
expectType<(string | boolean)[]>(
13+
arrify(new Set<string | boolean>(['🦄', true]))
1314
);
1415
expectType<number[]>(arrify(new Set([1, 2])));
1516
expectError(arrify(['🦄'] as const).push(''));
17+
expectType<number[] | []>(arrify(Boolean() ? [1, 2] : null));
18+
expectType<number[] | []>(arrify(Boolean() ? [1, 2] : undefined));
19+
expectType<number[] | [string]>(arrify(Boolean() ? [1, 2] : '🦄'));
20+
expectType<number[] | string[]>(arrify(Boolean() ? [1, 2] : ['🦄']));
21+
expectType<number[] | [boolean]>(arrify(Boolean() ? [1, 2] : true));
22+
expectType<number[] | [number]>(arrify(Boolean() ? [1, 2] : 3));
23+
expectType<number[] | [{}]>(arrify(Boolean() ? [1, 2] : {}));
24+
expectType<number[] | [number, string]>(
25+
arrify(Boolean() ? [1, 2] : [1, 'foo'])
26+
);
27+
expectType<number[] | (string | boolean)[]>(
28+
arrify(Boolean() ? [1, 2] : new Set<string | boolean>(['🦄', true]))
29+
);
30+
expectType<number[] | [boolean] | [string]>(
31+
arrify(Boolean() ? [1, 2] : Boolean() ? true : '🦄')
32+
);

0 commit comments

Comments
 (0)