Skip to content

Commit

Permalink
Arrayable: Make it more usable by removing readonly (#1003)
Browse files Browse the repository at this point in the history
  • Loading branch information
adduserwyw authored Dec 12, 2024
1 parent 20e71e9 commit a128f69
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
7 changes: 5 additions & 2 deletions source/arrayable.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ function bundle(input: string, output: Arrayable<string>) {
// …
for (const output of outputList) {
console.log(`write to: ${output}`);
console.log(`write to: ${output}`);
}
}
Expand All @@ -23,4 +23,7 @@ bundle('src/index.js', ['dist/index.cjs', 'dist/index.mjs']);
@category Array
*/
export type Arrayable<T> = T | readonly T[];
export type Arrayable<T> =
T
// TODO: Use `readonly T[]` when this issue is resolved: https://github.com/microsoft/TypeScript/issues/17002
| T[];
23 changes: 19 additions & 4 deletions test-d/arrayable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,22 @@ import type {Arrayable} from '../index';

declare const unknown: unknown;

expectType<Arrayable<string>>(unknown as string | readonly string[]);
expectType<Arrayable<string | {foo: number}>>(unknown as (string | {foo: number}) | ReadonlyArray<string | {foo: number}>);
expectType<Arrayable<never>>(unknown as /* never | */ readonly never[]);
expectType<Arrayable<string[]>>(unknown as string[] | readonly string[][]);
expectType<Arrayable<string>>(unknown as string | string[]);
expectType<Arrayable<string | {foo: number}>>(unknown as (string | {foo: number}) | Array<string | {foo: number}>);
expectType<Arrayable<never>>(unknown as /* never | */ never[]);
expectType<Arrayable<string[]>>(unknown as string[] | string[][]);

// Test for issue https://github.com/sindresorhus/type-fest/issues/952
type Item = number;
function castArray1(value: Arrayable<Item>): Item[] {
return Array.isArray(value) ? value : [value];
}

expectType<Item[]>(unknown as ReturnType<typeof castArray1>);

function castArray2<T>(value: Arrayable<T>): T[] {
return Array.isArray(value) ? value : [value];
}

expectType<number[]>(castArray2(1));
expectType<number[]>(castArray2([1, 2, 3]));

0 comments on commit a128f69

Please sign in to comment.