Skip to content

Type guards are not working properly in Observable #19334

Closed

Description

TypeScript Version: 2.5.3

Code

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/from';
import 'rxjs/add/operator/filter';

type AType = 'first' | 'second';

function isFirst(value: AType): value is 'first' {
  return value === 'first';
}

const inputs: AType[] = ['first', 'second'];
const obx = Observable.from(inputs);

obx
  .filter(item => isFirst(item)) // <- checking types with guard
  .subscribe(item => console.log(item)); // <- here item is still `'first' | 'second'`!

A simple example to reproduce.

Expected behavior:
Type guards must make sure the flow continues according to the current status of types.

Actual behavior:
Apparently because the type guard is not within a branch it is not working as intended, or it is working as intended by design that I personally think is not a good idea.

Activity

  1. aminpaks commented on Oct 20, 2017

    @aminpaks
    ContributorAuthor

    Andy (Andrewkraft) (@Andy-MS) I'm using [email protected], and tried with 5.5.0 but no difference!
    from rxjs:

    import { Observable } from '../Observable';
    export declare function filter<T, S extends T>(this: Observable<T>, predicate: (value: T, index: number) => value is S, thisArg?: any): Observable<S>;
    export declare function filter<T>(this: Observable<T>, predicate: (value: T, index: number) => boolean, thisArg?: any): Observable<T>;
  2. aminpaks commented on Oct 20, 2017

    @aminpaks
    ContributorAuthor

    I found this issue. Is this a duplication?

  3. aminpaks commented on Oct 20, 2017

    @aminpaks
    ContributorAuthor

    Andy (Andrewkraft) (@Andy-MS) you're missing the from -> import 'rxjs/add/observable/from'

  4. aminpaks commented on Oct 20, 2017

    @aminpaks
    ContributorAuthor

    I updated my question :)

  5. aminpaks commented on Oct 20, 2017

    @aminpaks
    ContributorAuthor

    Andy (Andrewkraft) (@Andy-MS) that's interesting! Thanks a lot.

  6. mhegazy commented on Nov 6, 2017

    @mhegazy
    Contributor

    Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

  7. locked and limited conversation to collaborators on Jun 14, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions