microsoft / microsoft/TypeScript

Allow composite values to be used in type predicates

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

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

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

説明

Allow composite values to be used in type predicates

🔍 Search Terms

Is, composite type, complex type, composite value, complex value, type 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

Type predicates allow you to define functions that can tell the TypeScript compiler if a parameter is of a certain type.
I suggest that this be extended to allow type predicates to narrow the type of composite objects involving parameters.
That is, the left-hand-side of is types should be allowed to include object literals.

📃 Example

Say you have a type that involves a subset of another type:

type MyType = {property1: "static text", property2: "Hello" | "World"};

A type predicate for this would always require passing in the property1 property, even though it’s unnecessary.
Now, you can create a type predicate that only takes the value of property2, but still gurantees the result type:

function foo(text: string): {property1: "static text", property2: text} is MyType {
    return ["Hello", "World"].includes(text);
};

I’ve run into the problem of being unable to do this while developing my website.
I had a tagged union:

type A = {t: "A", value: "X" | "Y"};
type B = {t: "B", value: string};
type U = A | B;

And I wanted to get a value of type A from user input, but default back to a B type if the value wasn’t
To do this, I hoped to be able to do this:

function zit(x: string): {t: "A", value: x} is A {
    return ["X", "Y"].includes(x);
};
function gob(x: string): U {
    return zit(x) ? {t: "A", value: x} : {t: "B", value: x};
};

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

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

はじめの一歩

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

調査の方向性

ファイル、テスト、エントリポイントは指定されていません。まず issue の type-predicate の例と、コンパイラに既にある type-guard の動作を確認してください。複合オブジェクト型が述語で受け入れられ、示されている narrowing のシナリオが、生成される JavaScript を変更せずに機能すれば、変更は完了です。

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

評価

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

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

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