microsoft / microsoft/TypeScript

Custom array index types

オープン
#40,648 コメント 2 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

Awaiting More Feedback Suggestion
主要言語
Go
スター
111k
フォーク
14.3k
平均マージ
1日 19時間
マージ済み PR(30日)
117

説明

Search Terms

custom array index type

Suggestion

Arrays are indexed by integers, cool. But they could also be indexed by something equivalent to an integer, like an enum-like class or wrapper around a number. For example:

class PlayerNumber { constructor(readonly n: number); valueOf() { return this.n; } }
let currentTurn = 3;
const players: Player[];
let currentPlayer = new PlayerNumber(4);

// correct
players[+currentPlayer]
// oops, typo, but no protection
players[+currentTurn]

Imagine we had a TypedArray<K extends { valueOf(): number }, V> that in all respects was like Array, except all array indices in any function signature were of type K, and all arrays in any function signature were instead TypedArray<K, ...>. And the + wouldn't be necessary. Then:

// correct AND AWESOME
players[currentPlayer]
// compiler error
players[currentTurn]

Use Cases

I am writing a game framework in TypeScript and there are just lots of arrays everywhere indexed by players, token types, round number, etc and it's easy to mess up which index goes where.

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.

I'm unclear on the last bullet. There is a bit of "operator overloading" involved in the proposal as suggested. I am not sure if that is disqualifying and/or if there is an alternative that would work.

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

まず、提案の TypedArray<K, V> モデルと、TypeScript が現在配列のインデックス参照および valueOf ベースの式をどのように型付けしているかを調べます。要求された型安全性が、ランタイムの変更なしに既存の型システムのルールに適合できるかを判断します。完了とは、対応する型チェックの動作とテストを伴う、具体的で受け入れられた設計が得られることを意味します。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
typescript
領域
compilers
issue の種類
機能追加
難易度
5/5
見積もり時間
1週間以上
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
25/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。