Closed
Description
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:
- get all candidate type of
p
- ensure NotNullable (that is, exclude
null
andundefined
) - try to match one type in all candidate types with the right object literal
- use the matched type as
ThisType
for the object literal's member functions.