Skip to content

Class members that are non-optional or are not unioned with undefined don't require initialisation. #20829

Closed
@kujon

Description

@kujon

TypeScript Version: 2.6.2 strict mode

Apologies if this is a duplicate, I wasn't able to find a relevant issue.

Code

class Foo {
    test: number;
}

const foo = new Foo();

foo.test; //> undefined

Expected behavior:
I'd expect the code above to blow up, because I've not assigned a value to the test member. The compiler could require me to do either of the following to address the issue (similarly to how e.g. Java behaves):

  1. Initialise in place:
class Foo {
    test: number = 42;
}
  1. Initialise in the constructor:
class Foo {
    test: number;
    constructor() {
        this.test = 42;
    }
}

Actual behavior:
The above code compiles.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions