镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
Skip to content

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

Description

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.

Activity

  1. j-oliveras commented on Dec 20, 2017

    @j-oliveras
    Contributor

    That will be one of the features of the next version. The pull request #20075 implement this. Roadmap with 2.7 features.

    You can try this feature with npm install -g typescript@next (more info about trying future versions).

  2. locked and limited conversation to collaborators on Jun 21, 2018
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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions