Skip to content

preset class properties to undefined #12437

Closed

Description

TypeScript Version: 2.1.1

Code

class PartialPolicySearchIten {
	public displayValue: string;
	public oriNumber: string;
	public parentName: string;
	public sysNumber: string;
	public systemCode: number;
	public systemName: string;
}

Expected behavior:

class PartialPolicySearchIten {
       constructor() {
        this.displayValue = undefined;
	this.oriNumber = undefined;
	this.parentName = undefined;
	this.sysNumber = undefined;
	this.systemCode = undefined;
	this. systemName = undefined;
       }
}

Actual behavior:
class PartialPolicySearchIten { }

The problem comes when using Reflection it can't find the properties. I would expected that the properties exists as i'm redefining them. Otherwise their very little point is declaring properties of a class.

Activity

  1. Jameskmonger commented on Nov 22, 2016

    @Jameskmonger

    You need to explicitly initialise them as undefined to have the effect you want.

    Input

    class ImplicitlyUndefinedProperties {
    	public foo: string;
    	public bar: string;
    }
    
    class ExplicitlyUndefinedProperties {
    	public foo: string = undefined;
    	public bar: string = undefined;
    }

    Output

    var ImplicitlyUndefinedProperties = (function () {
        function ImplicitlyUndefinedProperties() {
        }
        return ImplicitlyUndefinedProperties;
    }());
    var ExplicitlyUndefinedProperties = (function () {
        function ExplicitlyUndefinedProperties() {
            this.foo = undefined;
            this.bar = undefined;
        }
        return ExplicitlyUndefinedProperties;
    }());

    Therefore I think that this is not an issue but is intended behaviour.

  2. added
    Suggestion
    ES Next
    on Nov 22, 2016
  3. DanielRosenwasser commented on Nov 22, 2016

    @DanielRosenwasser
    Member

    While this is the original/current behavior, the current ES proposal seems to actually imply that a property will indeed be defined & set to undefined even without an initializer.

    https://tc39.github.io/proposal-class-public-fields/#initialize-public-static-fields

  4. added
    Bug
    Breaking Change
    on Jan 10, 2018
  5. RyanCavanaugh commented on Jan 10, 2018

    @RyanCavanaugh
    Member

    The proposal is now Stage 3 with this behavior. We need to discuss whether or not to take a break for this

  6. removed
    Bug
    on Apr 12, 2018
  7. added
    Waiting for TC39
    on Aug 15, 2018
  8. buschtoens commented on Dec 3, 2018

    @buschtoens

    (Public) class fields are enabled by default in Chrome 72 with the initializer semantics outlined above. This part of the spec is extremely unlikely to change. Current topics of debate are just how private fields should work AFAICT.

    Can we please revisit and get a decision here? While the Babel transform is not officially supported, they would want to wait for a decision by the TypeScript team before implementing any fixes: babel/babel#9105

    The major arguments for keeping the current semantics to me are:

    • no breakage
    • "re-typing" a class field in a derived class is easier.\

    In favor of switching:

    • spec compliancy
    • less cognitive load for JS developers migrating to TS

    Any input would be much appreciated ☺️❤️

  9. nicolo-ribaudo commented on Dec 4, 2018

    @nicolo-ribaudo
    Contributor
    • "re-typing" a class field in a derived class is easier.\

    For type-only information something like this could work:

    class Foo {
      public x: string; // initialized to undefined
      declare public y: string; // type-only
    }
  10. kutomer commented on Dec 4, 2018

    @kutomer

    Nicolò Ribaudo (@nicolo-ribaudo) not sure how it's possible, tried it on ts playground and got declare' modifier cannot appear on a class element.

  11. buschtoens commented on Dec 4, 2018

    @buschtoens

    Tomer Kruvi (@kutomer) I think what Nicolò Ribaudo (@nicolo-ribaudo) wanted to express is that the declare keyword could be used as new syntax, i.e. it does not work yet and would be a breaking change to TypeScript. 🙂

  12. nicolo-ribaudo commented on Dec 4, 2018

    @nicolo-ribaudo
    Contributor

    Yeah exactly

  13. chriskrycho commented on Dec 26, 2018

    @chriskrycho

    Also worth noting here that moving to spec compliance is a loud breaking change, because the existing types end up being wrong with strictNullChecks: true:

    class Foo {
      public x: string; // initialized to undefined
    }

    ☝️ would be wrong; the type would need to be:

    class Foo {
      public x?: string; // initialized to undefined
    }

    This will be a non-trivial breaking change to a lot of codebases. (It intersects with definite strictPropertyInitialization a bit as well.)

  14. 8 remaining items

  15. ljharb commented on Jun 8, 2020

    @ljharb
    Contributor

    Igor Szymański (@IgorSzymanski) the difference, however, is observable, and it's important for it to be correct.

  16. IgorSzymanski commented on Jun 10, 2020

    @IgorSzymanski

    Jordan Harband (@ljharb) I ask again for the use case.
    Also, if you do not initialise and optional property, why do you expect it to be initialised with undefined? If you do not initialise an optional property, the expected behaviour is it's not there, uninitialised shouldn't be initialised, and that's exactly what happens.

    Also, the OP example is horrible.

    If you define a property as non-optional number, it should be nothing else, but a number. No part of the code says it can be undefined.

  17. ljharb commented on Jun 10, 2020

    @ljharb
    Contributor

    Anything using object spread or Object.assign will care about it being a present, own property, even if set to undefined. undefined is not simply "not defined", in JS, there exists "absent", "present but set to undefined", and "present but set to non-undefined".

  18. IgorSzymanski commented on Jun 10, 2020

    @IgorSzymanski

    Then initialise your properties explicitly. This is a breaking change, it breaks the logic behind explicit property initialisation and, once again, I do not see any use case where it should matter.
    In OOP, you shouldn't really ask for properties of a class instance, because it breaks its encapsulation.
    In FP, you wouldn't even use a class for this, and therefore you would have to initialise the property on your own.
    This change is nothing but an attempt to encourage a bad programming style.

    I also do not see, why you would want to run a class instance against Object.assign or object spread. Mind to elaborate?

    Give me a valid example of why the lack of implicit property initialisation in a class instance is an issue.

  19. RyanCavanaugh commented on Jun 10, 2020

    @RyanCavanaugh
    Member

    Igor Szymański (@IgorSzymanski) this continual moving of the goalposts isn't indicative of a good-faith conversation. If you don't think it's important to you, that's fine, but no one is required to justify spec compliance as a valid goal

  20. ajakaja commented on Jun 10, 2020

    @ajakaja

    The reason I initially came across this issue, and wrote my comment above, is that I hit a case where an error was caused by this surprising logic. Unfortunately I cannot remember the exact example, but any similar example would be equivalent: if one writes

    class Foo {
      public x?: string;
    }
    

    and doesn't initialize the property, there should be some sort of warning.

    Otherwise

    const foo = Foo()
    console.log(foo.x); // typechecks, gives 'undefined'
    console.log(foo.hasOwnProperty('x')); // gives 'false'
    

    leads to confusion. For instance, sometimes one uses hasOwnProperty to implement a typeguard:

    function isFoo(foo: Foo | Bar): foo is Foo {
      return foo.hasOwnProperty('x')
    }
    

    which fails if Foo is defined as above, even though it might be an actual instance of Foo.

  21. IgnusG commented on Mar 9, 2021

    @IgnusG

    Any update on the spec compliance?

  22. RyanCavanaugh commented on Mar 9, 2021

    @RyanCavanaugh
    Member

    This is now the behavior under --useDefineForClassFields

  23. ljharb commented on Mar 9, 2021

    @ljharb
    Contributor

    Is that also now the default in tsc init?

  24. RyanCavanaugh commented on Mar 9, 2021

    @RyanCavanaugh
    Member

    Not yet, but we should probably change that.

  25. ljharb commented on Mar 9, 2021

    @ljharb
    Contributor

    Should this be reopened to track that, or would you prefer a separate issue?

  26. RyanCavanaugh commented on Mar 9, 2021

    @RyanCavanaugh
    Member

    Separate issue please. Thanks!

  27. ljharb commented on Mar 9, 2021

    @ljharb
    Contributor

    Filed #43167.

  28. ExE-Boss commented on Mar 10, 2021

    @ExE-Boss
    Contributor

    Looks like there’s already #39311.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Breaking ChangeES NextSuggestionWaiting for TC39

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions