Skip to content

Commit

Permalink
TypeScript - Fix handling of union types (#11)
Browse files Browse the repository at this point in the history
Fixes #8
Fixes #10
  • Loading branch information
BendingBender authored and sindresorhus committed Apr 9, 2019
1 parent f789ce5 commit e044bd1
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 9 deletions.
18 changes: 11 additions & 7 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,16 @@ arrify(undefined);
//=> []
```
*/
declare function arrify(value: null | undefined): [];
declare function arrify(value: string): [string];
declare function arrify<ValueType>(value: ValueType[]): ValueType[];
// TODO: Use 'readonly ValueType[]' in the next major version
declare function arrify<ValueType>(value: ReadonlyArray<ValueType>): ReadonlyArray<ValueType>;
declare function arrify<ValueType>(value: Iterable<ValueType>): ValueType[];
declare function arrify<ValueType>(value: ValueType): [ValueType];
declare function arrify<ValueType>(
value: ValueType
): ValueType extends (null | undefined)
? []
: ValueType extends string
? [string]
: ValueType extends ReadonlyArray<unknown> // TODO: Use 'readonly unknown[]' in the next major version
? ValueType
: ValueType extends Iterable<infer T>
? T[]
: [ValueType];

export = arrify;
21 changes: 19 additions & 2 deletions index.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,25 @@ expectType<string[]>(arrify(['🦄']));
expectType<[boolean]>(arrify(true));
expectType<[number]>(arrify(1));
expectType<[{}]>(arrify({}));
expectType<([string | number, string | number])[]>(
arrify(new Map<string | number, string | number>([[1, 2], ['a', 'b']]))
expectType<[number, string]>(arrify([1, 'foo']));
expectType<(string | boolean)[]>(
arrify(new Set<string | boolean>(['🦄', true]))
);
expectType<number[]>(arrify(new Set([1, 2])));
expectError(arrify(['🦄'] as const).push(''));
expectType<number[] | []>(arrify(Boolean() ? [1, 2] : null));
expectType<number[] | []>(arrify(Boolean() ? [1, 2] : undefined));
expectType<number[] | [string]>(arrify(Boolean() ? [1, 2] : '🦄'));
expectType<number[] | string[]>(arrify(Boolean() ? [1, 2] : ['🦄']));
expectType<number[] | [boolean]>(arrify(Boolean() ? [1, 2] : true));
expectType<number[] | [number]>(arrify(Boolean() ? [1, 2] : 3));
expectType<number[] | [{}]>(arrify(Boolean() ? [1, 2] : {}));
expectType<number[] | [number, string]>(
arrify(Boolean() ? [1, 2] : [1, 'foo'])
);
expectType<number[] | (string | boolean)[]>(
arrify(Boolean() ? [1, 2] : new Set<string | boolean>(['🦄', true]))
);
expectType<number[] | [boolean] | [string]>(
arrify(Boolean() ? [1, 2] : Boolean() ? true : '🦄')
);

0 comments on commit e044bd1

Please sign in to comment.