你可以将它定义为一个generic实用程序类型HasSameKeysAs<T, U>
,它的计算值总是为U
,但除非它有与T
完全相同的键,否则它会抱怨:
type HasSameKeysAs<
T, U extends {
[P in keyof T | keyof U]: P extends keyof T ? any : never
}> = U;
这是因为U
对于依赖于T
和U
的类型来说是constrained.我们在T
和U
的两个键上都有map.任何存在于T
中的密钥都将被要求并允许为任何东西(与any
),而存在于U
中但不存在于T
中的任何密钥将被强制为不可能的never
类型,这基本上禁止了它(好吧,它允许never
,但这不太可能意外地出现).至少对于你的示例用例来说没有).
让我们试试看:
type SameKeysWithNeyTypes = HasSameKeysAs<Numbers, {
a: string;
b: Date;
}> // error!
// Property 'f' is missing in type '{ a: string; b: Date; }'
// but required in type '{ a: any; b: any; f: any; }'.
type SameKeysWithNeyyTypes = HasSameKeysAs<Numbers, {
a: string;
b: Date;
c: null;
f: 1;
}> // error!
// Types of property 'c' are incompatible.
type SameKeysWithNeyyyTypes = HasSameKeysAs<Numbers, {
a: string;
b: Date;
f: 1;
}> // okay
看起来不错缺少键和额外键会导致错误,而具有完全相同键的类型工作正常.
Playground link to code