首页 文章

Typescript Compiler无法调用类型缺少调用签名的表达式

提问于
浏览
0

我正在使用Array(来自JavaScript)和List(来自facebook immutable库) . 我创建了以下功能:

fooFunc(descriptors: List<Descriptor> | Array<Descriptor>) {
  let descriptor = descriptors.find(d => d.game == game);
}

编译器说:

无法调用类型缺少调用签名的表达式 .

两个对象都有一个找到相同签名的方法 .

有任何想法吗?

我正在使用TypeScript版本:2.0.2

1 回答

  • 1

    看起来两者的签名是不同的:

    Array.find

    find(
        predicate: (value: T, index: number, obj: Array<T>) => boolean, 
        thisArg?: any
    ): T | undefined;
    

    List.find

    find(
        predicate: (value?: V, key?: K, iter?: /*this*/Iterable<K, V>) => boolean,
        context?: any,
        notSetValue?: V
    ): V;
    

    因为它们具有不同的签名,所以它们的并集将不允许您使用find方法 . 例如:

    interface A {
        fn(a: number): void;
    }
    
    interface B {
        fn(a: string): void;
    }
    
    type both = A | B;
    let a: both;
    a.fn(3); // error: Cannot invoke an expressions whose type lacks a call signature
    

    那是因为 a.fn 的类型为 (a: number) => void | (a: string) => void ,不可调用 .
    与您的示例相同 .

    由于您只对值感兴趣,因此两个签名都可以为您工作,因此您可以将其转换为其中一个:

    let descriptor = (descriptors as Array<Descriptor>).find(d => d.game == game);
    

    这将工作得很好 .
    另一种选择是这样做:

    type MyArrayType<T> = (Immutable.List<T> | Array<T>) & {
        find(predicate: (value: T) => boolean): T;
    }
    
    function fooFunc(descriptors: MyArrayType<Descriptor>) {
        let descriptor = descriptors.find(d => d.game == game);
    }
    

相关问题