打字稿检查类型A ===类型B | C型

Mar*_*com 4 types assert typeof typescript keyof

在一个文件中,我有这样的东西:

export const _all = {
  a: '',
  b: '',
  c: '',
  d: '',
  e: '',
  f: '',
}
type AllKeysType = typeof _all;
export type AllKey = keyof AllKeysType;
Run Code Online (Sandbox Code Playgroud)

在另一个文件中,我有这样的东西:

export const _keep = {
  a: '',
  b: '',
  d: '',
  e: '',
}
type KeepKeysType = typeof _keep;
export type KeepKey = keyof KeepKeysType;

export const _ignore = {
  c: '',
  f: '',
}
type IgnoreKeysType = typeof _ignore;
export type IgnoreKey = keyof IgnoreKeysType;
Run Code Online (Sandbox Code Playgroud)

如何使用Typescript断言在_allALWAYS中定义的键始终等于_keep和的并集_ignore。换句话说,AllKey应始终等于KeepKey| IgnoreKey

我希望Typescript编译器给我一个错误,如果开发人员_all通过添加新值(例如z)进行更新,却忘记了添加z_keep或中_ignore

Dav*_*ret 6

这可以通过定义条件类型来实现,该条件类型接受两种类型并解析为true输入类型相等或false相反。然后编写一些代码,当该类型为not时将引发编译错误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);
Run Code Online (Sandbox Code Playgroud)

更强大的代码是一个长一点(例如在处理该any类型),但它卷起在我的图书馆在这里

import { assert, IsExact } from "conditional-type-checks";

// define or import AllKey, KeepKey, IgnoreKey

assert<IsExact<AllKey, KeepKey | IgnoreKey>>(true);
Run Code Online (Sandbox Code Playgroud)

另外一个选项

另一个不太好做的方法是创建两个类型的两个对象,并将它们彼此分配。

() => {
  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;
};
Run Code Online (Sandbox Code Playgroud)