microsoft / microsoft/TypeScript
instanceof AbstractClass.constructor should narrow to typeof AbstracClass
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
Please try to reproduce the issue with
typescript@next. It may have already been fixed.
TypeScript Version: 3.3.0-dev.20181208
Search Terms: static instanceof constructor
Code
type Meta = {foo: string};
abstract class Abstract {
static meta: Meta;
public abstract toString(): string;
}
const getMeta = (fromModule: any): Meta | undefined => {
return fromModule instanceof Abstract.constructor
? fromModule.meta : undefined;
};
Expected behavior:
Narrow the type of fromModule to typeof Abstract, so that static fields can be accessed.
(In Typescript versions <= 3.1.6 the above code didn't raise an error, my guess is that the type was not narrowed at all)
Actual behavior:
The narrowed type of fromModule is {}:
Error:(10, 18) TS2339: Property 'meta' does not exist on type '{}'.
Related Issues:
I found the following potentially related issues but they didn't seem to be an exact match or to old (because this problem only exists since 3.2.1):
- #27276
- #23274
- #16035
Workaround
Creating a type guard is of course doable for a single abstract class.
const extendsAbstract = (FromModule: unknown): FromModule is typeof Abstract =>
FromModule && FromModule instanceof Abstract.constructor;
(Or maybe it could even be written in a generic way?)
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing the example in the linked TypeScript Playground with typescript@next, then compare the behavior with the reported 3.3.0-dev.20181208 version. Review related issues #27276, #23274, and #16035 before tracing the compiler's instanceof narrowing behavior. Done means the example narrows fromModule to typeof Abstract so the static meta field is accepted, with coverage for the regression.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100