microsoft / microsoft/TypeScript

Using types from private class properties results in `any` types in `.d.ts` files

Open
#60,230 4 comments 2 reactions 1 assignee View on GitHub

@weswigham is already working on this.

Since Oct 30, 2024.

Bug Domain: Declaration Emit
Dominant language
Go
Stars
111k
Forks
14.4k
Avg merge
1d 19h
Merged PRs (30d)
117

Description

🔎 Search Terms

class private any index access

🕗 Version & Regression Information
  • This is the behavior in every version I tried, and I reviewed the FAQ for entries
⏯ Playground Link

https://www.typescriptlang.org/play/?#code/KYDwDg9gTgLgBAYwDYEMDOa4DEITgbwCg4S4woBLANxRmDgH1yIxhYBPALjjRkoDsA5nAC8cAOTiA3MVIII-XlACuCGNAAUKKIO44IAbXFMoLNjHbiAugEoCskgF9CzoA

💻 Code
export class Foo {
    private _property: string = '';
    constructor(arg: Foo['_property']) {
    }
}

🙁 Actual behavior

Generated .d.ts is:

export declare class Foo {
    private _property;
    constructor(arg: Foo['_property']);
}
🙂 Expected behavior

Generated .d.ts is:

export declare class Foo {
    private _property: string;
    constructor(arg: Foo['_property']);
}
// or
export declare class Foo {
    private _property;
    constructor(arg: string);
}
// or
/* Typescript Errors on the code to tell you it's going to generate an `any` */
Additional information about the issue

This behaviour is problematic because it creates a desync between consumers of .ts files and consumers of .d.ts files for the same code.

For example:

new Foo(1);

If the Foo type comes from the .ts file, then TS will error on this code as it can see that the argument type is string.
OTOH if the Foo type comes from the .d.ts file, then TS will NOT error on this code as it sees the argument type as any.


We have just uncovered this at Canva.
A user reported an error showing up in their IDE against our master branch (i.e. code that has passed CI as typechecked).
The code is structured such that the file with the error (A) is in a separate project to the file declaring the class (B).
This means that we have the exact scenario above where (A) consumes (B)'s .d.ts during our CLI builds, but (A) consume's (B)'s .ts within the IDE.

This pattern of declaring a type based on a private property's type is quite pervasive across our codebase and it's surprising that this is the first problem that's been actively revealed.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.