我有一个映射类型Minus<A,B>
用于创建一个包含A上所有属性的类型,除了那些也在B上的属性,定义如下:
type Diff<T extends string, U extends string> = ({[P in T]: P } & {[P in U]: never } & { [x: string]: never })[T];
/**
* Type T without any of the properties on U.
*/
export type Minus<T, U> = {[P in Diff<keyof T, keyof U>]: T[P]};
例如,如果我有两个接口,A
interface A {
thing1: string;
thing2: number;
}
和B
interface B {
thing1: string;
}
然后Minus<A, B>
应该产生相当于的类型
interface C {
thing2: number;
}
这种方法很有效,直到我在A上有可选类型,因为这些类型在整个过程中都会丢失。
用qzxswpoi取代
A
将导致类似的类型
interface A {
thing1: string;
thing2?: number;
}
而不是期望的
interface C {
thing2: number;
}
有趣的是,interface C {
thing2?: number;
}
的行为似乎确实保留了属性是否可选; Readonly会产生一个相当于的类型
Readonly<T>
所以我怀疑这与我的Diff类型有关。
有没有人有一个解决方案可以保留interface ReadonlyA {
readonly thing1: string;
readonly thing2?: number;
}
上的属性是否可选?
Minus<A, B>
哪个会正确保留可选类型。
感谢type Diff<T extends string, U extends string> = ({[P in T]: P } & {[P in U]: never } & { [x: string]: never })[T];
/**
* Type T without any of the properties on U.
*/
export type Minus<T, U> = Pick<T, Diff<keyof T, keyof U>>;
指出我在右边