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

Add Arrayable type #270 #935

Merged
merged 2 commits into from
Aug 12, 2024
Merged

Add Arrayable type #270 #935

merged 2 commits into from
Aug 12, 2024

Conversation

Max10240
Copy link
Contributor

fix #270

@Max10240 Max10240 changed the title Add TypeName type #270 Add Arrayable type #270 Aug 11, 2024
source/arrayable.d.ts Outdated Show resolved Hide resolved
source/arrayable.d.ts Outdated Show resolved Hide resolved
source/arrayable.d.ts Outdated Show resolved Hide resolved
@sindresorhus sindresorhus merged commit 9aabcb9 into sindresorhus:main Aug 12, 2024
8 checks passed
@Max10240
Copy link
Contributor Author

Max10240 commented Sep 2, 2024

@fregante Item cannot be an array type, because Arrayable<unknown[]> is equivalent to unknown[] | readonly unknown[][], NOT unknown[] or readonly unknown[]. If Item is an Array type, Array.isArray will always return true, meaning that the actual return type of castArray1 / castArray2 is actually Item itself, not Item[].
I'm guessing what you're looking for is something like:

import { Arrayable } from 'type-fest';

type Primitive =
	| bigint
	| boolean
	| null
	| number
	| string
	| symbol
	| undefined;

function castArray<Item extends Primitive | Record<PropertyKey, unknown>>(value: Arrayable<Item>): Item[] {
	return Array.isArray(value) ? value : [value];
}

@fregante
Copy link
Collaborator

fregante commented Sep 2, 2024

My previous code worked correctly if readonly is dropped, so that lengthy type information is a consequence of this keyword.

You can see it working here: https://www.typescriptlang.org/play/?#code/JYWwDg9gTgLgBAbwIJSgQwJ5oEYBsCmAvnAGZQQhwDkMGY+AtCfgM4xUDcAUF7fXAAVcaYADsU6LHnwAeABoA+OAF44cuAB81AbQC63HiQCuogMYxgEUXFNo2EzAEYZASRj4QCgBQA3NLiN8AC5BYTEHKQJXd08AShC3Dz1ELgBIKHwYIyhrCIA6YBYI339A2LgAfjg-APw4EO0awP0uQkMTc0trW3tUTAAmaI9vJuC4CJwoxLiEmOSENIysnPG+jAKitZLa8qrR+rhG0vwWtqA

In your case, it doesn't even support regular class instances, like castArray(new Date())

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Like Promisable<X> but for arrays: X | X[]
4 participants