Skip to content

strictNullChecks does not detect assertions done before property access #13652

@connium

Description

@connium

TypeScript Version: 2.1.5

Code
In my jasmine tests I use .toBeDefined(...) to check whether the tested value is filled properly.

interface Person {
  name: string;
  address?: Address;
}

interface PersonService {
  getByName(name: string): Person;
}

it('should work as expected', () => {
  const person = personService.getByName('Norris');

  expect(person.address).toBeDefined();
  expect(person.address.state).toEqual('Oklahoma');
});

Running the compiler with strictNullChecks enabled results in a error TS2532: Object is possibly 'undefined'. on the line where person.address.state is accessed.

Checking explicitly for undefined resolves this issue:

it('should work as expected', () => {
  const person = personService.getByName('Norris');

  if (person.address === undefined) {
    throw new Error('address is undefined');
  }
  expect(person.address.state).toEqual('Oklahoma');
});

As this is a common pattern in my code, I thought it would be a good idea to extract the check in order to keep the tests clean and simple.

function assertNotUndefined(value: any): void|never {
  if (value === undefined) {
    throw new Error('value is undefined');
  }
}

it('should work as expected', () => {
  const person = personService.getByName('Norris');

  assertNotUndefined(person.address);
  expect(person.address.state).toEqual('Oklahoma');
});

Now I get the compiler error again.

Expected behavior:
The compiler does not complain about access to an potentially undefined variable when --strictNullChecks is set.

Actual behavior:
The compiler says error TS2532: Object is possibly 'undefined'.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions