microsoft / microsoft/TypeScript

Generic rest of intersection should be assignable to its type parameter constituents

オープン
#28,636 コメント 4 件 リアクション 6 件 担当者 0 名 GitHub で見る

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

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

説明

Search Terms

generic rest intersection type parameter

Suggestion

The rest of an intersection containing type parameters and object types should be assignable to the type parameters if the rest removed all the properties from the object types. For example:

function ripoff<T>(augmented: T & { a }): T {
  const { a, ...original } = augmented;
  return original;
}

This is technically not safe — the instantiation of the type parameters could overlap with the object types — but it is how higher-order spread currently behaves. I believe the most common use of rest is with disjoint types. (Spread is similar, but identical types is the most common use there.)

One way to allow this is to create a new assignability rule:

Pick<T & U & ... & { a } & { b } & ..., Exclude<keyof T & U & ..., 'a' | 'b' | ...>> ⟹ T & U & ...

In prose, the rule is that the pick of an intersection that consists of only type parameters and object types is assignable to the intersection of the type parameters if the second argument is an Exclude, and the Exclude's first argument is keyof the intersection of the type parameters, and the Exclude's second argument is the keys of the intersection of the object types.

Another optional is a simpler rule, where the pick of any intersection with a type parameter T is assignable to T:

Pick<T & ..., Exclude<keyof T & ..., K>> ⟹ T

Note that these rules don't cover what to do with constrained type parameters. The second rule is inaccurate enough already that it probably doesn't matter, but the first rule should probably have an additional restriction on Exclude's second argument.

Use Cases

React HOCs basically all do this.

Examples

From this comment:

import React, { Component } from 'react'

import { Counter } from './counter-render-prop'
import { Subtract } from '../types'

type ExtractFuncArguments<T> = T extends (...args: infer A) => any ? A : never;

// get props that Counter injects via children as a function
type InjectedProps = ExtractFuncArguments<Counter['props']['children']>[0];

// withCounter will enhance returned component by ExtendedProps
type ExtendedProps = { maxCount?: number };

// P is constrained to InjectedProps as we wanna make sure that wrapped component
// implements this props API
const withCounter = <P extends InjectedProps>(Cmp: React.ComponentType<P>) => {
  class WithCounter extends Component<
    // enhanced component will not include InjectedProps anymore as they are injected within render of this HoC and API surface is gonna be extended by ExtendedProps
    Subtract<P, InjectedProps> & ExtendedProps
  > {
    static displayName = `WithCounter(${Cmp.name})`;

    render() {
      const { maxCount, ...passThroughProps } = this.props;

      return (
       // we use Counter which has children as a function API for injecting props
        <Counter>
          {(injectedProps) =>
            maxCount && injectedProps.count >= maxCount ? (
              <p className="alert alert-danger">
                You've reached maximum count! GO HOME {maxCount}
              </p>
            ) : (
              // here cast to as P is needed otherwise compile error will occur
              <Cmp {...injectedProps as P} {...passThroughProps} />
            )
          }
        </Counter>
      );
    }
  }

  return WithCounter;
};

// CounterWannabe implement InjectedProps on it's props
class CounterWannabe extends Component<
  InjectedProps & { colorType?: 'primary' | 'secondary' | 'success' }
> {
  render() {
    const { count, inc, colorType } = this.props;

    const cssClass = `alert alert-${colorType}`;

    return (
      <div style={{ cursor: 'pointer' }} className={cssClass} onClick={inc}>
        {count}
      </div>
    );
  }
}

// if CounterWannabe would not implement InjectedProps this line would get compile error
const ExtendedComponent = withCounter(CounterWannabe);

Checklist

My suggestion meets these guidelines:

  • This probably wouldn't be a breaking change in existing TypeScript/JavaScript code. Would need to be tested.
  • 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.

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

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

はじめの一歩

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

調査の方向性

issue にはソースファイルもテストのエントリポイントも指定されていません。まず ripoff の例と React HOC の例から始め、次に、制約付き型パラメーターと重複する型を含め、提案された 2 つの代入可能性ルールを比較してください。示された cast なしで、指定された交差型の残りがそれぞれの型パラメーターの構成要素に代入可能になれば完了です。

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

評価

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

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

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