【问题标题】:Typescript subtracted type打字稿减去类型
【发布时间】:2019-01-13 20:56:34
【问题描述】:

是否有可能在 Typescript 中创建减法类型? 我正在考虑一个用户案例,当 React 组件只向组件用户公开 if 道具的子集时。 React-redux 连接示例:

import {Component, ComponentType} from 'react';

export function connect<S, A>(state: () => S, actions: A){
  return function createConnected<P>(component: ComponentType<P>){
    return class Connect extends Component<P-S-A>{ // <-- 
      // ...
    }    
  }
}

阅读后: Exclude property from type

似乎我得到了这个工作......

import {Component, ComponentType} from 'react';

type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;

function connect<S, A>(state: () => S, actions: A) {
    return function createConnect<P extends S & A>(C: React.ComponentType<P>): ComponentType<Omit<P, keyof S | keyof A>> {
        return class Connect extends Component<Omit<P, keyof S | keyof A>> {
            // ...
        };
    };
}

....但我不明白怎么做。


更新 2:

在玩了这个之后,我发现了一种更简洁的方式(在我看来),来描述一个减法类型:

// LeftOuterJoin
type Subtract<T, V> = Pick<T, Exclude<keyof T, keyof V>>;

function connect<S, A>(state: () => S, actions: A) {
    return function createConnect<P>(C: ComponentType<P>) {
        return class Connect extends Component<Subtract<P, S & A>> {
                  // ...
        };
    };
}

【问题讨论】:

  • Exclude property from type 的可能重复项。使用该问题中的 Omit 类型,您可以将类型写为 Omit&lt;P, keyof S | keyof A&gt;

标签: reactjs typescript react-redux tsx


【解决方案1】:

....但我不明白怎么做。

这里使用内置的Exclude 类型来操作字符串文字的联合。

Exclude&lt;keyof T, K&gt; 排除 keyof T 中位于 K 中的所有键,假设 K 也是字符串文字的联合 - 并且约束 K extends keyof T 确保,声明 K 必须是T 的键子集。

另一个内置类型 Pick&lt;T, K&gt; 允许从 T 创建一个新类型,该类型仅具有 K 中的键 - 再次假设 K 是字符串文字的并集和keyof T.

使用PickExclude 作为构建块,您可以将一种类型从另一种类型中减去类型表示为“仅从一种类型中选择不存在于另一种类型中的这些属性”,而Exclude 执行“不存在” " 按键操作。

这里是扩展的形式,将ComponentPropsProps不包括SA中的道具:

type ComponentProps = Pick<Props, Exclude<keyof Props, keyof S | keyof A>>

【讨论】:

  • 看来Exclude&lt;keyof Props, keyof (S &amp; A)&gt; 也可以。 keyof S | keyof A这部分对我来说仍然没有意义......
  • 两者是等价的。想象一下{foo: string}{bar: number}keyof S -&gt; 'foo'keyof A -&gt; 'bar',因此,它们的联合keyof S | keyof A -&gt; 'foo' | 'bar'。交集S &amp; A -&gt; {foo: string; bar: number},其keyof也是'foo' | 'bar'
  • @Nabuska 是的 keyof (S &amp; A)keyof S | keyof A 的类型完全相同。交集类型必须具有其所有成员类型的属性,即其属性是交集成员类型属性的并集。另见stackoverflow.com/a/38857724/43848
猜你喜欢
  • 2021-12-18
  • 1970-01-01
  • 2019-07-26
  • 1970-01-01
  • 2021-11-26
  • 1970-01-01
  • 2021-03-20
  • 2019-05-03
  • 2020-10-12
相关资源
最近更新 更多