我想定义一个泛型类型 ExcludeCart<T>
这本质上是 T
但是删除了给定的 key (在我的例子中是 cart
)。所以,例如,ExcludeCart<{foo: number, bar: string, cart: number}>
将是 {foo: number, bar: string}
.有没有办法在 TypeScript 中执行此操作?
这就是我想要这样做的原因,以防我找错了树:我正在将现有的 JavaScript 代码库转换为 TypeScript,其中包含一个名为 cartify
的装饰器函数。采用 React 组件类 Inner
并返回另一个组件类 Wrapper
.
Inner
应该采取 cart
Prop ,以及零个或多个其他 Prop 。 Wrapper
接受 cartClient
prop(用于生成 cart
传递给 Inner
的 prop),以及 Inner
的任何 prop接受,除了 cart
.
换句话说,一旦我弄清楚如何定义ExcludeCart
,我想用它来做这个:
function cartify<P extends {cart: any}>(Inner: ComponentClass<P>) : ComponentClass<ExcludeCart<P> & {cartClient: any}>
最佳答案
TypeScript 3.5 更新: Omit<Type, Keys>
实用程序类型现在可用。请看Mathias' answer示例用法。
旧答案:自TypeScript 2.8以及 Exclude
的介绍, 现在可以这样写了:
type Without<T, K> = {
[L in Exclude<keyof T, K>]: T[L]
};
或者更简洁地说,如:
type Without<T, K> = Pick<T, Exclude<keyof T, K>>;
对于您的用法,您现在可以编写以下内容:
type ExcludeCart<T> = Without<T, "cart">;
关于reactjs - TypeScript:从类型/减法类型中删除键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41476063/