是否可以限制对象属性的数量,假设我想限制对象只有一个字符串属性(具有任何名称),我可以这样做:
{[index: string]: any}
限制属性的类型,但是可以限制属性的数量吗?
Stackoverflow 上这个问题有很多答案(包括这个详细的),但它们都不适合我的情况,这与此处发布的情况类似。
Problem
我有一个接受对象的函数。我想让它抛出一个编译错误(打字稿)如果传递的对象没有恰好一个键。例如
f({}); // Must error here, as it has less than one key!
f({ x: 5 });
f({ x: 5, y : 6 }); // Must error here, as it has more than one key!
Solution
使用流行的并集到交集 and IsUnion,我通过以下实用函数实现了它。
type SingleKey<T> = IsUnion<keyof T> extends true ? never : {} extends T ? never : T;
完整代码:
// From https://stackoverflow.com/a/50375286
type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
// From: https://stackoverflow.com/a/53955431
type IsUnion<T> = [T] extends [UnionToIntersection<T>] ? false : true;
// Here we come!
type SingleKey<T> = IsUnion<keyof T> extends true ? never : {} extends T ? never : T;
// Usage:
function f<T extends Record<string, any>>(obj: SingleKey<T>) {
console.log({ obj });
}
f({}); // errors here!
f({ x: 5 });
f({ x: 5, y : 6 }); // errors here!
游乐场链接
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)