【问题标题】:How to use array methods with union type elements?如何将数组方法与联合类型元素一起使用?
【发布时间】:2019-03-09 10:17:11
【问题描述】:

我有以下代码:

class A {}

class B {}

const arr = [new A(), new B()]

function findB(): B {
    return arr.find<B>(el => el instanceof B)
}

我遇到了一个错误

类型'A | B' 不可分配给类型'B'。 类型“A”中缺少属性“b”,但类型“B”中需要。

与“过滤器”等方法相同。

interface Array<T> {
    find<S extends T>(predicate: (this: void, value: T, index: number, obj: T[]) => value is S, thisArg?: any): S | undefined;
    find(predicate: (value: T, index: number, obj: T[]) => boolean, thisArg?: any): T | undefined;
}

基于“数组”定义,将这些方法与联合类型一起使用的唯一方法是重写接口吗?比如这样

interface Array<T> {
    find<S>(predicate: (this: void, value: T, index: number, obj: T[]) => boolean, thisArg?: any): S | undefined;
}

或者有其他方法可以解决这个问题?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    定义守卫“el is B”。它可以工作(即使在严格模式下)

    class A {}
    
    class B {}
    
    const arr = [new A(), new B()]
    
    function findB(): B | undefined {
        return arr.find((el): el is B => el instanceof B);
    }
    
    function filterB(): B[] {
        return arr.filter((el): el is B  => el instanceof B);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-03
      • 1970-01-01
      • 2013-09-03
      • 1970-01-01
      相关资源
      最近更新 更多