Skip to content

Interface or Class with only optional properties does not do type checking #14673

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
tobalsgithub opened this issue Mar 15, 2017 · 2 comments
Closed
Labels
Duplicate An existing issue was already created

Comments

@tobalsgithub
Copy link

TypeScript Version: 2.1.4

Code

class AllOptionalClass {
  optional?: string;
}

let x = new AllOptionalClass();
x = 'asdf'; // good

class RequiredClass {
  requiredClass: string;
}

let y = new RequiredClass();
y = 'asdf'; // Type '"asdf"' is not assignable to type 'RequiredClass'

interface IAllOptional {
  optional?: string;
}

let a : IAllOptional = {
  optional: 'asdf'
};

a = 'asdf'; // good

interface IRequired {
  required: string;
}

let b : IRequired = {
  required: 'asdf'
};

b = 'asdf'; // Type '"asdf"' is not assignable to type 'IRequired'

Expected behavior:
I would expect x = 'asdf'; to fail with the same error as y = 'asdf';, and I would expeect a = 'asdf'; to fail with the same error as b = 'asdf';

Actual behavior:
A variable that has a type of a class or interface with all optional properties can have anything assigned to it as far as I can tell.

@tobalsgithub
Copy link
Author

It may be worth noting that the way I came across this was actually in a class that implements an interface with only optional properties.

interface IAllOptional {
  optional?: string;
}

interface RecordClass {
  optional? : IAllOptional;
}

class AllOptional implements RecordClass {
  optional: number; // would expect this to be an error
}

@mhegazy
Copy link
Contributor

mhegazy commented Mar 15, 2017

Please see #7485

@mhegazy mhegazy added the Duplicate An existing issue was already created label Mar 15, 2017
@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants