Error when converting BehaviourSubjects in Angular

Discussão em 'Angular' iniciado por Marc, Janeiro 21, 2025.

  1. Marc

    Marc Guest

    Let's assume we have two interfaces:

    interface A {
    name: string;
    _id?: string;
    }

    interface B {
    name: string;
    _id: string;
    }


    When assigning them to each other, typescript behaves like I would expect it:

    const a: A = { name: 'a' };
    const b: B = { name: 'b', _id: '1' };
    const c: B = a; //
    const d: A = b;

    const getA = (): A => {
    return b;
    };


    In line 3, I'm getting the following error:

    TS2322: Type A is not assignable to type B
    Types of property _id are incompatible.
    Type string | undefined is not assignable to type string
    Type undefined is not assignable to type string


    That make sense, because the _id of a could be undefined.

    When I use A with an BehaviourSubject likt this, I'm also getting an error:

    const behA = new BehaviorSubject<A>(a);
    const behB = new BehaviorSubject<B>(b);

    const getBehA = (): BehaviorSubject<A> => {
    return behB;
    }


    S2322: Type BehaviorSubject<B> is not assignable to type BehaviorSubject<A>
    Types of property observers are incompatible.
    Type Observer<B>[] is not assignable to type Observer<A>[]
    Type Observer<B> is not assignable to type Observer<A>
    Type A is not assignable to type B
    Types of property _id are incompatible.
    Type string | undefined is not assignable to type string
    Type undefined is not assignable to type string


    For me it is not really clear why. If I try the same with a simple container interface, it works fine:

    interface Container<T> {
    value: T;
    }
    const getCA = (): Container<A> => {
    return cB;
    }


    (Don't know what to write here)

    Continue reading...

Compartilhe esta Página