Skip to content

Uninitialized class properties with type undefined are allowed, breaking type expectations for class instances.Β #55195

Closed as not planned
@RobertSandiford

Description

@RobertSandiford

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

Playground

πŸ’» 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

  1. new C produces an empty object c
  2. TS thinks that c has a property a, based on the class definition
  3. Assignment to o: O is allowed
  4. in function f, TS identifies that the else branch doesn't occur
  5. running f(o) or f(c) results in the else branch running

Output

[LOG]: C: {} 
[LOG]: "This never happens" 

πŸ™‚ Expected behavior

-strict mode was on

  1. 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)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Not a DefectThis behavior is one of several equally-correct options

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions