typescript - 键入两个对象以确保它们不共享任何键
问题描述
我想写一个有两个参数的函数,每个参数都是一个对象。这些对象不得共享密钥。如何键入此约束?
// helpers
const a=1, b=2, c=3, d=4;
// how do I type this function?
function func(x, y) {/*...*/}
func({a, b, c}, {d}) // ok; no keys are shared
func({a, b}, {b, c}) // Error; key `b` is shared.
或者提出:我如何约束一个类型,使其不包含另一种类型的键?
const foo = {a, b};
type X = typeof foo;
type NoKeysOf<S> = {/*... */}; // <- How do I constrin this type?
const bar: NoKeysOf<X> = {d}; // ok; no keys shared
const baz: NoKeysOf<X> = {b, c} // Error; `b` is shared
解决方案
您可以在编译时使用never类型强制执行这种约束。
declare function f<
A,
B extends { [K in keyof B]: K extends keyof A ? never : B[K] }
>(
a: A, b: B
): any
我们在这里要说的是,如果K
是 的一个键B
,扩展了 的一个键A
,则其对应的值 inb
将是类型never
(因此,您永远无法构造它),否则,它将只是B[K]
。
这正是所需的行为:
const a = 1, b = 2, c = 3, d = 4;
f({ a, b, c }, { d }) // OK
f({ a, b }, { b, c }) // Error: Type 'number' is not assignable to type 'never'
推荐阅读
- c# - 如何在 Blazor 中更新绑定变量的类
- android - addOnSuccesListener 执行顺序问题,firebase 存储
- python - 使用python在数据库中插入utf8的问题
- date - 如何在 Flutter 中传递返回小部件的三元
- javascript - 从子组件更新父状态在 reactjs 中不起作用
- c++ - 是否可以在 Exception 对象中存储有关错误的信息?
- excel - Power Query - 加权平均
- ios - NETunnelProviderSession startTunnel() 不启动 VPN 连接
- node.js - 如何选择流中的特定块来使用 Axios 和 nodejs
- javascript - 我们如何使用 express 在 nodeJS 中实现管理面板?