π Search Terms
const type generic parameter class anonymous
π Version & Regression Information
- I was unable to test this on prior versions because it is a TypeScript 5 new feature.
β― Playground Link
https://www.typescriptlang.org/play/?#code/CYUwxgNghgTiAEAzArgOzAFwJYHtXwxAGcMAeMPE+ANXhAA9DVgj4cAjAK3AwD4AKAG5QIyEAC4aASknUA3ACgFFVFWEQsweAF4CxDPwDeSHDkkBtAOTtYlgLrwAvlMXLKGeCSjYwASVTqmjp6JPyQUESshgrwsfAA9PHwAKIwMDgwkgAqAMoA7AAMAExF8JaIppbwWAC2AA4aYFgYEACe8AAWEQStdQiWUKitVezgUMhECM3wwDjE8Kg4Hl2CCFA9ffCDixjeuPiDWliscIggcOggWsBYcJhtbDDVzLc8D1j4zaw4AO6fqM0sCIsAAvc4AOhicS8PngcCgs1QDwqOGCVhsMHsimcrhUVA+Xku-kCWl0hFC4Ui8GicThIAReGRpjR1lsdmxLgUiXgxOBWgwvQkngwMA+AHNzA4CYQEWxEPB0WyFKgQD9noSwCBeRpgPwpOCUQogA
π» Code
declare function test<const V extends object>(value: V): V;
const valid = test({ foo: ['bar'] });
const staticInvalid = test(class {
// Error: TS7022 'foo' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.
static readonly foo = ['bar'];
});
const instanceInvalid = test(class {
readonly foo = ['bar'];
});
// Invalid type: string[] instead of ['bar']
new instanceInvalid().foo
π Actual behavior
TS7022 error appears on the static foo property.
- Type is
string[] on the instance foo property.
π Expected behavior
No error should be emitted, and static/instance foo properties should have the same type as with an object literal: ['bar'].
Additional information about the issue
In practice, both object literal and class static array properties could be changed.
But if const type parameters work on object literal, why not on classes static/instance properties?
π Search Terms
const type generic parameter class anonymous
π Version & Regression Information
β― Playground Link
https://www.typescriptlang.org/play/?#code/CYUwxgNghgTiAEAzArgOzAFwJYHtXwxAGcMAeMPE+ANXhAA9DVgj4cAjAK3AwD4AKAG5QIyEAC4aASknUA3ACgFFVFWEQsweAF4CxDPwDeSHDkkBtAOTtYlgLrwAvlMXLKGeCSjYwASVTqmjp6JPyQUESshgrwsfAA9PHwAKIwMDgwkgAqAMoA7AAMAExF8JaIppbwWAC2AA4aYFgYEACe8AAWEQStdQiWUKitVezgUMhECM3wwDjE8Kg4Hl2CCFA9ffCDixjeuPiDWliscIggcOggWsBYcJhtbDDVzLc8D1j4zaw4AO6fqM0sCIsAAvc4AOhicS8PngcCgs1QDwqOGCVhsMHsimcrhUVA+Xku-kCWl0hFC4Ui8GicThIAReGRpjR1lsdmxLgUiXgxOBWgwvQkngwMA+AHNzA4CYQEWxEPB0WyFKgQD9noSwCBeRpgPwpOCUQogA
π» Code
π Actual behavior
TS7022error appears on the staticfooproperty.string[]on the instancefooproperty.π Expected behavior
No error should be emitted, and static/instance
fooproperties should have the same type as with an object literal:['bar'].Additional information about the issue
In practice, both object literal and class static array properties could be changed.
But if
consttype parameters work on object literal, why not on classes static/instance properties?