有没有办法指定类型中已定义的键?
interface KeyType {
userName: string,
address: string
}
type ValidationType = {
userName: ValidateUserNameType;
address: ValidateAddressType;
}
这些 KeyType
和 ValidationType
用于不同的用途,但 ValidationType
键将始终与 KeyType
相同>.
我四处寻找,但没有运气
最佳答案
您可以定义强制执行相同键的自定义类型:
type SameKeys<T, U extends Record<keyof T, any>> =
{ [K in keyof U]: K extends keyof T ? U[K] : never }
// e.g.
type SameKeysValidationType = SameKeys<KeyType, ValidationType>
U
必须扩展 T
中的所有键。如果U
有更多属性,它们将被解析为never
值类型。但这不会引发编译错误 - 这里有两个选项:
接口(interface)扩展
interface ValidationType extends SameKeys<KeyType, ValidationType> {
userName: ValidateUserNameType;
address: ValidateAddressType; // comment => compile error
// foo: string // uncomment => compile error
}
断言类型
// generic assert type
type AssertSameKeys<T, U extends Record<keyof T, any> & SameKeys<T, U>> = true
// this will error, when ValidationType is not proper
type AssertValidationType = AssertSameKeys<KeyType, ValidationType>
以上变体适用于您的情况。您仍然应该评估和测试您想要对可选属性和其他边缘情况执行的操作。
关于javascript - 在 typescript 中指定 keyof 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60371530/