microsoft / microsoft/TypeScript
Narrowing for key type by `in` operator
まだ誰も着手していません。
- 主要言語
- Go
- スター
- 111k
- フォーク
- 14.3k
- 平均マージ
- 2日 4時間
- マージ済み PR(30日)
- 132
説明
Suggestion
A k in v check should narrow type of k: K to K & keyof typeof v.
🔍 Search Terms
in operator narrowing
✅ 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 code should compile due to narrowing on x:
const o = {foo: 1, bar: 2} as const;
const x: string = 'foo';
if (x in o) {
const y: "foo" | "bar" = x; // OK
}
Currently it could be made with custom type guard
const in_ = <K extends string, O>(key: K, object: O): key is K & keyof O => key in object;
if (in_(x, o)) {
const y: "foo" | "bar" = x; // OK
}
📃 Motivating Example
When validating a JSON with some kind of AST (or otherwise containing a tagged union) the only type we can have for a tag is a string.
const validateDisjointUnion = <O extends object>(
nodeTypeValidators: { [K in keyof O]: (value: O[K]) => boolean },
value: Json,
) => {
if (typeof value !== 'object' || !('type' in value)) throw 42;
const {type} = value;
if (typeof type !== 'string' || !(type in nodeTypeValidators)) throw 42;
// expression of type 'string' can't be used to index type '{ [K in keyof O]: (value: O[K]) => boolean; }'.
return nodeTypeValidators[type](value);
}
💻 Use Cases
in_ solves the issue, but it involves a type guard. Type guards are "dangerous" in a sense that they can be used improperly (for example, !(key in object) would compile as well, but would lead to runtime error).
There is a related feature request to narrow type for second parameter of in operator. As far as I'm aware, there is no syntax to specify type of in_ that would guard on both parameters at the same time.
const guardBoth = <A, B>(a: A, b: B): (a is string) & (b is string) => { ... };
Edit. Not even
// A type predicate cannot reference a rest parameter.(1229)
const in_ = <K extends string, O, T>(...args: [K, O]): args is [K & keyof O, O & { [L in K]: unknown }] => args[0] in args[1];
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
ファイルやテストは指定されていません。まず in チェックとカスタム type guard を示している TypeScript の例から始め、次にコンパイラーが in 演算子のオペランドをどのように絞り込むかを追ってください。動機となるケースでキーが K & keyof typeof v に絞り込まれ、出力される JavaScript を変更しなければ完了です。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- typescript
- 領域
- compilers
- issue の種類
- 機能追加
- 難易度
- 5/5
- 見積もり時間
- 1週間以上
- 活発さ
- 停滞
- 明瞭さ
- 明確に書かれている
- 初心者へのやさしさ
- 35/100