创建一个接受对象但不接受数组的通用函数
Create a generic function that takes objects but does not take arrays
我想创建一个满足此要求的通用 TypeScript 函数:
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!
所以我不知道如何以通用方式键入参数或 return 类型,以便它接受任何对象(以及 returns 它)但不拿一个数组。我想使用类型而不是在运行时使用 Array.isArray
.
尝试使用 Conditional Type 比如:
type NotArray<T> = T extends Array<unknown> ? never : T;
function f<T>(arg: NotArray<T>) {
}
对于任何数组类型参数都会失败
我想创建一个满足此要求的通用 TypeScript 函数:
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!
所以我不知道如何以通用方式键入参数或 return 类型,以便它接受任何对象(以及 returns 它)但不拿一个数组。我想使用类型而不是在运行时使用 Array.isArray
.
尝试使用 Conditional Type 比如:
type NotArray<T> = T extends Array<unknown> ? never : T;
function f<T>(arg: NotArray<T>) {
}
对于任何数组类型参数都会失败