Skip to content

Option to treat { [integer]: T } as T[] #573

@taminomara

Description

@taminomara

Currently, I have to annotate all functions that take an array with T[] | { [integer]: T }. I'd like to see a more ergonomic way of doing this. While { [integer]: T } does not strictly imply that the table will be used as an array, I think it's a common enough pattern to allow it.

Use case: having an array with some additional data.

--- @class A
--- @field [integer] string Array elements.
--- @field data any Some additional data.

--- @param a string[]
function takesArray(a) end

takesArray({} --[[@as A]]) -- `A` is not an array.

Possible alternatives:

Inheriting class from an array, or using an alias doesn't work as well, so there's currently no way to express an array with additional fields:

--- @alias A string[] & { data: any }

--- @param a string[]
function takesArray(a) end

takesArray({} --[[@as A]]) -- complains that `A` is not an array
--- @class A: string[]
--- @field data any Some additional data.

--- @param a string[]
function takesArray(a) end

takesArray({} --[[@as A]]) -- also complains that `A` is not an array.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions