Closed as not planned
Description
Bug Report
π Search Terms
class properties with type undefined properties produce objects that don't match inferred type
π Version & Regression Information
Present between 3.3 and 5.2.0 nightly.
β― Playground Link
π» Code
type O = {
a: undefined
}
class C { // new C will produce an empty object, because a is not initialized
a: undefined
}
const c = new C
console.log(c) // c is { }
type TOC = keyof typeof c // "a" - typescript thinks 'c' has a property 'a'
const o: O = c // allowed to assign to type O
function f(o: O) {
if ('a' in o) {
console.log('a exists')
} else {
const never: never = o
console.log('This never happens')
}
}
f(o)
π Actual behavior
new C
produces an empty objectc
- TS thinks that
c
has a propertya
, based on the class definition - Assignment to
o: O
is allowed - in function
f
, TS identifies that theelse
branch doesn't occur - running
f(o)
orf(c)
results in theelse
branch running
Output
[LOG]: C: {}
[LOG]: "This never happens"
π Expected behavior
-strict mode was on
- strictPropertyInitialization check should catch that
a
is not initialized, and throw an error
Note: If useDefineForClassFields is true, which occures by default for target >= ES2022, JS is emitted which initializes the property, and there is no problem. Bug exists only for cases of useDefineForClassFields: false (includes the default TS config)