microsoft / TypeScript

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
https://www.typescriptlang.org
Apache License 2.0
98.27k stars 12.2k forks source link

Private class properties prevent `Readonly` type inference #58347

Closed Trombecher closed 2 weeks ago

Trombecher commented 2 weeks ago

🔎 Search Terms

"type inference readonly private class property", "generic type inference"

🕗 Version & Regression Information

⏯ Playground Link

https://www.typescriptlang.org/play/?ts=5.5.0-dev.20240428#code/MYGwhgzhAEBiD28A8AVAfNA3gKGtADgE4CWAbmAC4Cm0A+kfPgPwBc0KA3NgL7bYUBPfDQCSAOwBmVQkljQqAD2piAJjATIwYgWgwBeOPKVVV6xEmKTp7DE3bQ2EsCAhUu2EFQp1qECm3EpGQ0kCkIAVypdLk9vWl8KACYAqxkAJSowFXgxEAFZczDI3TQOaAB6cugkAFpoAAN4qj9E+uhiGHrwsQBreAB3MTbiCThEADp6QkZ2mCIySipxoA

💻 Code

class Foo<T> {
  private _prop?: T;
}

type Infer<F extends Foo<any>> = F extends Foo<infer T> ? T : false;

let _test: Infer<Foo<true>>;
let _test2: Infer<Readonly<Foo<true>>>; // <- `_test2` is `unkown` if Foo._prop is private.

🙁 Actual behavior

The type of the variable _test2 is unknown.

Since Readonly<Foo<T>> extends Foo<T> there is no reason that TypeScript cannot infer T.

🙂 Expected behavior

The type of _test2 should be true or whatever T is (inferred).

Additional information about the issue

If the private modifier from _prop is removed, _test2 correctly shows true or whatever T is. A property modifier should not influence type inference.

Trombecher commented 2 weeks ago

nvm Readonly removes private types (???)

MartinJohns commented 2 weeks ago

See #50668 and others.