请考虑以下事项:
type U = {a: string, b: string};
type T = U & ({c: string, d?: never}|{c?: never, d: string});
type E = Exclude<T, {a: string}>;
type O = Omit<T, "a">;
const t1: T = {a: "a", b: "b", c: "c", d: "d"}; // error - expected
const t2: T = {a: "a", b: "b", c: "c"}; // ok - expected
const t3: T = {a: "a", b: "b", d: "d"}; // ok - expected
const e1: E = {b: "foo", c: "c", d: "d"}; // error - expected
const e2: E = {b: "foo", c: "c"}; // error: E is never
const e3: E = {b: "foo", d: "d"}; // error: E is never
const o1: O = {b: "foo", c: "c", d: "d"}; // ok - unexpected!
const o2: O = {b: "foo", c: "c"}; // ok
const o3: O = {b: "foo", d: "d"}; // ok
类型T
被定义为包含属性a
和b
的对象and或c
或d
,但not两者都包含.
我正在try 构造一个与T
except相同的类型,它没有a
属性.我try 了Exclude
和Omit
,从上面可以明显看出,这两种方法都不能满足我的需求.
有没有一种方法可以在不事先知道类型T
的 struct 的情况下,从类型T
的黑盒中删除一个属性,并保持它的其他所有内容不变?
还打字here个操场.
Edit:修复了原始类型;添加了更多测试用法
Edit #2:这道题与Typescript: Omit a property from all interfaces in a union, but keep the union structure题不同,因为:
- 所讨论的类型不是直线并集,而是一侧包含并集的交集
- 它还解决了从任意"黑盒"类型中删除的属性而不更改其任何其他语义的问题.