microsoft / microsoft/TypeScript
Suggestion: Allow getters to have predicate return types
まだ誰も着手していません。
- 主要言語
- Go
- スター
- 111k
- フォーク
- 14.4k
- 平均マージ
- 1日 19時間
- マージ済み PR(30日)
- 117
説明
Suggestion
🔍 Search Terms
getter, predicate, type guard
✅ Viability 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, new syntax sugar for JS, etc.)
- [✅] This feature would agree with the rest of TypeScript's Design Goals.
⭐ Suggestion
This has been requested before (e.g., #6994) but declined because at the time getters were merely an aspect of implementation. Since that is no longer the case, would there be any interest in revisiting the suggestion?
📃 Motivating Example
class Person {
name?: string;
}
class Thing {
constructor(public owner: Person | null = null) {}
get isOwned(): this is Owned<this> {
return !!this.owner;
}
}
type Owned<T extends Thing> = T & { owner: NonNullable<T['owner']> };
💻 Use Cases
I have a use case much like the above. Currently type narrowing by checking thing.owner isn't honored when thing is used as a function argument:
function doSomethingWithOwnedThing(ownedThing: Owned<Thing>) {}
declare const thing: Thing;
if (thing.owner) {
thing.owner.name; // ok
doSomethingWithOwnedThing(thing); // not ok (thing.owner is possibly `null`)
}
With the above, I can create a normal function or method that returns a type predicate or otherwise simply assert that thing is an Owned<Thing>. Given that user-defined type guards are encapsulated type assertions, and getters are shiny and neat, a boolean getter that doubles as a type guard would be nicest.
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
まず issue の getter と type guard の例を確認し、次に #6994 の以前の議論と、リンクされた #43036 の設計に関する議論を比較してください。提案された getter の戻り値の型が受け入れられ、示されている Owned<Thing> の絞り込みが、出力される JavaScript を変更せずに機能すれば完了です。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- typescript
- 領域
- compilers
- issue の種類
- 機能追加
- 難易度
- 5/5
- 見積もり時間
- 1週間以上
- 活発さ
- 静か
- 明瞭さ
- おおむね明確
- 初心者へのやさしさ
- 42/100