【发布时间】:2018-10-03 09:34:42
【问题描述】:
尝试创建一个函数,该函数接受一个不能有某些键集的单个参数对象,而不需要人们手动指定类型。我试图以某种方式利用never,但我正忙于理解推理如何适用于接受具有泛型参数的类型的函数参数。
interface ReservedAttributes {
someKey: string
}
// evaluates to never if the type has a key that intersects
// with the keys in ReservedAttributes
type ValidAttributes<T> = keyof T extends Exclude<keyof T, keyof ReservedAttributes> ? T : never
// This is correctly a never, but it doesn't address this problem
type Test = ValidAttributes<{someKey : string}>
// This doesn't work because the function argument ends
// up being inferred as { [name: string] : string}
function foo1<K extends { [name: string] : string}>(attributes: ValidAttributes<K>) {
// ...
}
foo1({a: 'hi', someKey: ''})
// Roughly equivalent to the above
function foo2< K extends { [name: string] : string}, V extends ValidAttributes<K> >(attributes: V) {
// ...
}
// This one allows V to correctly evaluate to never,
// but I'm not sure how to leverage that
function foo3< K extends { [name: string] : string}, V extends ValidAttributes<K> >(attributes: K) {
// ...
}
foo3({a: 'hi', someKey: ''})
你会如何解决这个问题?
【问题讨论】:
标签: typescript