我想创建一个满足以下条件的通用类型脚本函数:
f({ a: 1 }); // success
f(undefined); // success
f([]); // should fail the type check
f([1, 2]); // should fail the type check
换句话说,该函数不应该允许将数组作为参数传递,而应该接受对象。
问题是,该数组在JavaScript中是一个对象。即使这样也是有效的:
const x: Record<string, any> = ['test']; // works!
所以我不知道如何以泛型的方式输入参数或返回类型,以便它接受任何对象(并返回它),但不接受数组。我希望使用类型,而不是在运行时使用Array.isArray
。
尝试使用Conditional TypeLike:
type NotArray<T> = T extends Array<unknown> ? never : T;
function f<T>(arg: NotArray<T>) {
}
对于任何数组类型参数都将失败