Skip to content

ThisType may be null unexpectly if strictNullChecks is enabled #14504

Closed
@gdh1995

Description

@gdh1995

TypeScript Version: nightly (2.3.0-dev.20170307)

Code

// a.ts
type Point = {
    x: number;
    y: number;
    moveBy(dx: number, dy: number): void;
}

let p: Point | null;
p = {
    x: 10,
    y: 20,
    moveBy(dx, dy) {
        this.x += dx;  // this has type Point
        this.y += dy;  // this has type Point
    }
};

and the tsconfig.json is

{
  "compilerOptions": {
    "noImplicitThis": true,
    "strictNullChecks": true
  }
}

Expected behavior:

tsc compiles a.ts without any error.

Actual behavior:

It reports:

a.ts(13,9): error TS2531: Object is possibly 'null'.
a.ts(14,9): error TS2531: Object is possibly 'null'.

Propose

I think this is a bug because in most situations we won't want a "nullable" this in a object literal's member functions.

It's encouraging that #14141 has been merged, but there still seems to be some inconvenient rules.
In the case above, a better design might be:

  1. get all candidate type of p
  2. ensure NotNullable (that is, exclude null and undefined)
  3. try to match one type in all candidate types with the right object literal
  4. use the matched type as ThisType for the object literal's member functions.

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFixedA PR has been merged for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions