这可以通过定义一个接受两种类型并解析为的条件类型来实现true
当输入类型相等或false
否则。然后编写一些代码,当该类型不是时会抛出编译错误true
.
当任何一种类型发生更改时,您都会收到编译错误,这将确保您记住更新不同步的类型。当您想要收到有关不同库中类型更改的通知时,这尤其有用。
例如:
type IsExact<T, U> = [T] extends [U] ? [U] extends [T] ? true : false : false;
function assert<T extends true | false>(expectTrue: T) {}
// this will throw a compile error when the two types get out of sync
assert<IsExact<AllKey, KeepKey | IgnoreKey>>(true);
更健壮的代码会更长一些(例如处理any
类型),但它已经在我的图书馆里了here https://github.com/dsherret/conditional-type-checks.
import { assert, IsExact } from "conditional-type-checks";
// define or import AllKey, KeepKey, IgnoreKey
assert<IsExact<AllKey, KeepKey | IgnoreKey>>(true);
另外一个选择
另一种不太好的方法是创建两种类型的两个对象并将它们分配给彼此。
() => {
let allKeys: AllKey;
let otherKeys: KeepKey | IgnoreKey;
// do this in lambdas to prevent the first assignment from changing
// the type of the variable being assigned to
() => allKeys = otherKeys;
() => otherKeys = allKeys;
};