0

I have the following code:

class A {}

class B {}

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

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

I got an error

Type 'A | B' is not assignable to type 'B'. Property 'b' is missing in type 'A' but required in type 'B'.

The same with "filter" and other methods.

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;
}

Based on "Array" definition the only way to use those methods with union types is by overriding interface? Like this for example

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

Or there are other ways to solve this problem?

0

1 Answer 1

1

Define guard "el is B". It works (even in strict mode)

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.