小编Cli*_*lfe的帖子

除了函数之外的任何类型的 Typescript 泛型类型

structuredClone或者lodash.cloneDeep无法克隆函数。

有没有办法从泛型中排除Function类型?

我尝试过object: Exclude<T, {[key: string|number|symbol]: any, apply: any, call: any}>和 ,当对象作为类object: Exclude<T, Function>传入时,两者都会返回类型错误。this

function cloneAnythingButFunction1<T>(object: Exclude<T, {[key: string|number|symbol]: any, apply: any, call: any}>): T{
    return structuredClone(object)}

function cloneAnythingButFunction2<T>(object: Exclude<T, Function>): T{
    return structuredClone(object)
}

// Expect error:
cloneAnythingButFunction1(cloneAnythingButFunction1)
cloneAnythingButFunction2(cloneAnythingButFunction2)

// Expect no error:
class Test{
    clone1(){
        return cloneAnythingButFunction1(this) // error
    }
    clone2(){
        return cloneAnythingButFunction2(this) // error
    }
}
const test = new Test()
cloneAnythingButFunction1(test)
cloneAnythingButFunction2(test)
Run Code Online (Sandbox Code Playgroud)

TypeScript 游乐场

有没有什么办法解决这一问题?

typescript

3
推荐指数
1
解决办法
1287
查看次数

标签 统计

typescript ×1