Home > front end >  Type T | null is not assignable to type string | null. How come?
Type T | null is not assignable to type string | null. How come?

Time:04-26

I have a parent component, that uses a child component with an input binding like so:

// parent.component.html
<my-child [myBinding]="myObserVable$ | async"></my-child>

and its controller:

// parent.component.ts
public myObservable$ = new Subject<string>();

private someFunctions(event: string) {
    this.myObservable$.next(event);
}

The child component's controller:

// my-child.component.ts
@Input()
set myBinding(value: string | null) {
    // ...
}

Everything works fine. The observable is of type string and the async pipe (can) add a null to it, but IntellJ underlines "myObservable$ | async" redly and shows up Type T | null is not assignable to type string | null on hovering. enter image description here

Am I doing anything wrong and can I modify the code in order to fix the issue?

CodePudding user response:

T doesn't match string signature. You can either use type narrowing to make sure that T matches with string, or more likely in your case you can force T to match string signature using something like <T extends string>.

CodePudding user response:

declaring the type of myObservable$ fixed the red underline. So I changed

// parent.component.ts
public myObservable$ = new Subject<string>();

to

// parent.component.ts
public myObservable$: Subject<string> = new Subject<string>();

and the error linting gone byebye:

enter image description here

  • Related