Skip to content

Recursively-typed array with nth-element typing #32967

Closed
@harrysolovay

Description

@harrysolovay

Search Terms

• recursive (tuple|array) of varying length
• differently-typed array elements
• tuple of (generic|unknown) size

Suggestion

Ability to recursively type the elements of varying-length arrays

Use Cases

I'm attempting to create a type for hypertext nodes. Consider the following representation of some HTML:

["div", {"id": "parent"},
  ["div", {"id": "first-child"}, "I'm the first child"],
  ["div", {"id": "second-child"}, "I'm the second child"]
]

This is similar to the arguments of React's createElement. While it's possible to type the arguments array of a function and account for rest spread type... this doesn't seem doable in a standalone array. Meanwhile, tuples must be of fixed length. One solution would be to define this hypertext within call expressions:

h("div", {id: "parent"},
  h("div", {id: "first-child"}, "I'm the first child"),
  h("div", {id: "second-child"}, "I'm the second child"),
)

However, this format is more bloated. It doesn't convey the most minimal format for the data. My sense is that I should––for the time being––make use of any[].

By the way, apologies if this is currently possible and I just did not find it! Looked for quite a while & no approach seemed to do the trick.

Examples

export type HypertextNodeStructure<T, P, C> = [T, P, ...C[]];
export interface HypertextNode
  extends HypertextNodeStructure<string, {[key: string]: any}, HypertextNode> {}

const hypertextNode: HypertextNode =
  ["div", {id: "parent"},
    ["div", {id: "first-child"}, "I'm the first child"],
    ["div", {id: "second-child"}, "I'm the second child"]
  ]

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

Metadata

Metadata

Assignees

Labels

Fix AvailableA PR has been opened for this issueSuggestionAn idea for TypeScript

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions