Omit 不是类型安全的有什么理由吗?
这是一个示例 (see it in codesandbox):
interface IFoo {
foo: string;
bar: string;
baz: string;
}
type SomeFromFoo11 = Omit<IFoo, "foo" | "bar">;
// Omit some proops that doesn't exist.
type SomeFromFoo21 = Omit<IFoo, "wrong" | "ups">;
我希望最后一行给出编译时错误。
如果在某个时间将 foo.bar
重命名为 foo.bar2
,则不会产生错误。
Omit 可以用更安全的方式写成这样:
export type TypeSafeOmit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
type SomeFromFoo12 = TypeSafeOmit<IFoo, "foo" | "bar">;
// Compile time error below
type SomeFromFoo22 = TypeSafeOmit<IFoo, "wrong" | "ups">;
所以有一个解决方法,我只是想知道为什么原生 Omit 不能像这样工作。