【发布时间】: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<P, keyof S | keyof A>
标签: reactjs typescript react-redux tsx