Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Arrayable: Make it more usable by removing readonly #1003

Merged
merged 4 commits into from
Dec 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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]));
Loading