Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 类型脚本检查类型A==类型B |类型C_Typescript_Types_Assert_Typeof_Keyof - Fatal编程技术网

Typescript 类型脚本检查类型A==类型B |类型C

Typescript 类型脚本检查类型A==类型B |类型C,typescript,types,assert,typeof,keyof,Typescript,Types,Assert,Typeof,Keyof,在一个文件中,我有如下内容: export const _all = { a: '', b: '', c: '', d: '', e: '', f: '', } type AllKeysType = typeof _all; export type AllKey = keyof AllKeysType; export const _keep = { a: '', b: '', d: '', e: '', } type KeepKeysType = typ

在一个文件中,我有如下内容:

export const _all = {
  a: '',
  b: '',
  c: '',
  d: '',
  e: '',
  f: '',
}
type AllKeysType = typeof _all;
export type AllKey = keyof AllKeysType;
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;
在另一个文件中,我有如下内容:

export const _all = {
  a: '',
  b: '',
  c: '',
  d: '',
  e: '',
  f: '',
}
type AllKeysType = typeof _all;
export type AllKey = keyof AllKeysType;
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;
如何使用Typescript断言
\u all
中定义的键始终等于
\u keep
\u ignore
的并集。换句话说,
AllKey
应始终等于
KeepKey
|
IgnoreKey


如果开发人员通过添加新值(例如
z
)来更新
\u all
,我希望Typescript编译器给我一个错误但是忘记将
z
添加到
\u keep
\u ignore
这可以通过定义一个条件类型来实现,该条件类型接受两种类型,当输入类型相等时解析为
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);
另一个选项

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

() => {
  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;
};

非常感谢,assert函数非常有效!