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

empty class acts as "any" type: by design or bug? #5451

Description

The following typechecks fine:

class Empty {
}

// From a strongly-typed point of view, this feels strange
var e1: Empty = "Strange";
var e2: Empty = 42;

This also compiles

class Foo {
    name: string;

    constructor(name: string) {
        this.name = name;
    }

    hello() {
        return "456";
    }
}

class Bar {
    name: string;

    hello() {
        return "123";
    }
}

var foo = new Foo("Jo");

// From a strongly-typed point of view, this feels strange
var bar: Bar = foo;

Is this by design?

Activity

  1. RyanCavanaugh commented on Oct 29, 2015

    @RyanCavanaugh
    Member
  2. binarez commented on Nov 16, 2015

    @binarez

    I'm using typescript in an educational situation and would find useful to have a stricter mode that doesn't allow this special case. Is there any way to disable this? I found a work-around : adding a dummy private member makes not empty (obviously).

    class Empty
    {
        private dummy : any;
    }
    
    let e : Empty = 2;
    
    Type 'number' is not assignable to type 'Empty'. Property 'dummy' is missing in type 'Number'.
    

    I use '_' instead of 'dummy' in my lib (empty File class, it's really just a handle for the user, no attributes or methods) but you get the idea.

  3. RyanCavanaugh commented on Nov 16, 2015

    @RyanCavanaugh
    Member

    There isn't a way to disable this behavior using a flag or other setting. Adding a member to each class is the best solution.

  4. binarez commented on Nov 17, 2015

    @binarez

    Is adding one an option or is it too tied to the type system? I haven't read the type system docs you provided above, yet.

  5. RyanCavanaugh commented on Nov 17, 2015

    @RyanCavanaugh
    Member

    This isn't something we'd add an option for. It's a structural type system, so empty types are equivalent by definition.

  6. locked and limited conversation to collaborators on Jun 19, 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

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions