Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ThisType may be null unexpectly if strictNullChecks is enabled #14504

Closed
gdh1995 opened this issue Mar 7, 2017 · 0 comments
Closed

ThisType may be null unexpectly if strictNullChecks is enabled #14504

gdh1995 opened this issue Mar 7, 2017 · 0 comments
Assignees
Labels
Bug A bug in TypeScript Fixed A PR has been merged for this issue

Comments

@gdh1995
Copy link
Contributor

gdh1995 commented Mar 7, 2017

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.
@ahejlsberg ahejlsberg self-assigned this Mar 7, 2017
@ahejlsberg ahejlsberg added the Bug A bug in TypeScript label Mar 7, 2017
@ahejlsberg ahejlsberg added this to the TypeScript 2.3 milestone Mar 7, 2017
@ahejlsberg ahejlsberg added the Fixed A PR has been merged for this issue label Mar 7, 2017
@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Bug A bug in TypeScript Fixed A PR has been merged for this issue
Projects
None yet
Development

No branches or pull requests

2 participants