Skip to content

Add TupleOf type #161

@piotrwitek

Description

@piotrwitek

Is your feature request related to a real problem or use-case?

Add a generic way to specify length of a tuple type

Describe a solution including usage in code example

// From @ahejlsberg PR https://github.com/microsoft/TypeScript/pull/40002
type TupleOf<T, N extends number> = N extends N ? number extends N ? T[] : _TupleOf<T, N, []> : never;
type _TupleOf<T, N extends number, R extends unknown[]> = R['length'] extends N ? R : _TupleOf<T, N, [T, ...R]>;

type Vector<Length extends number> = TupleOf<number, Length>
type Matrix<Rows extends number, Columns extends number> = TupleOf<TupleOf<number, Columns>, Rows>

const v: Vector<2> = [1, 2]
const m: Matrix<2, 3> = [
  [1, 2, 3],
  [1, 2, 3],
]

Additional context (optional)

microsoft/TypeScript#40002

https://www.typescriptlang.org/play?ts=4.1.0-beta#code/C4TwDgpgBAKgrmANhA8gMwDwwDRQHJQQAewEAdgCYDOUZcAtgEYQBOAfFALy0PMuEly1fFAD8sANoBdKAC4oAfXhJUmHPlzS2AbgBQoSIuXJ0WXAWKlKNOk1a4ASgKvC4ZANZkA9gHcyWrigHCQByZDIAc2AACxCZSyEaAnEneSUEEzVzTXUAOnyHKR1dfXBoGABGQONVDCpgFgBLSNwAZh0oKAB6LqgJeqaWqAHmiNwRyKlSwxgAJmqM2ts+XAAGKAAfKHmtgBYO7t7pTb7l+x47FhktiTOWXDuH3nO7qYNy1oWVU0eLvgOen9WNJpuVdl9MhhfhVVqsAb0ACIQMAxQgsFheFhAA

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions