Skip to content

Control flow not working as expected outside of if block #10706

Closed
@watzon

Description

@watzon

TypeScript Version: 2.0.2 and nightly (2.0.0-dev.20160904)

Code

// A *self-contained* demonstration of the problem follows...
public test(records: IRecord | IRecord[]) {
  if (!Array.isArray(records)) {
    records = Array(records); // or records = [records]
  }
  return records.length;
}

Expected behavior:

Length should return the length of the array since I casted records to an array if it comes in as a single IRecord.

Actual behavior:

I get the error: Property length does not exist on type 'IRecord | Record[]'.

Workaround:
Not ideal

public test(records: IRecord | IRecord[]) {
  let _records: IRecord[];
  if (!Array.isArray(records)) {
    _records = Array(records);
  } else {
    _records = records;
  }
  return _records.length;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions