Typescript 2.8:从一种类型中删除另一种类型的属性

2023-12-01

In the 2.8 的变更日志,他们有条件类型的示例:

type Diff<T, U> = T extends U ? never : T;  // Remove types from T that are assignable to U
type T30 = Diff<"a" | "b" | "c" | "d", "a" | "c" | "f">;  // "b" | "d"

我想做到这一点,除了删除对象的属性。我怎样才能实现以下目标:

type ObjectDiff<T, U> = /* ...pls help... */;

type A = { one: string; two: number; three: Date; };
type Stuff = { three: Date; };

type AWithoutStuff = ObjectDiff<A, Stuff>; // { one: string; two: number; }

好吧,利用你的Diff之前的类型(顺便说一句,这与Excludetype 现在是标准库的一部分),你可以写:

type ObjectDiff<T, U> = Pick<T, Diff<keyof T, keyof U>>;
type AWithoutStuff = ObjectDiff<A, Stuff>; // inferred as { one: string; two: number; }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Typescript 2.8:从一种类型中删除另一种类型的属性 的相关文章

随机推荐