【问题标题】:Create a generic function that takes objects but does not take arrays创建一个接受对象但不接受数组的泛型函数
【发布时间】:2020-03-31 02:41:30
【问题描述】:

我想创建一个满足这一点的通用 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!

所以我不知道如何以通用方式键入参数或返回类型,以便它接受任何对象(并返回它)但不接受数组。我想使用类型而不是在运行时使用Array.isArray

【问题讨论】:

    标签: typescript typescript-typings typescript-generics


    【解决方案1】:

    尝试使用Conditional Type 之类的:

    type NotArray<T> = T extends Array<unknown> ? never : T;
    
    function f<T>(arg: NotArray<T>) {
    
    }
    

    对于任何数组类型参数都将失败

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-20
    • 1970-01-01
    • 1970-01-01
    • 2013-07-14
    • 2011-06-30
    • 1970-01-01
    • 2019-07-28
    • 1970-01-01
    相关资源
    最近更新 更多