- Notifications
You must be signed in to change notification settings - Fork 13k
Closed
Labels
DuplicateAn existing issue was already createdAn existing issue was already created
Description
Hi,
I am trying to perform a destructuring assignment in a method signature using a variable that is declared as an interface that has an optional property. I'm getting an error when specifying multiple levels of defaults.
Please take a look at the following code. I expected test number 3 to compile cleanly, but it gives an error. Tests 2 and 5 give what I think is an appropriate error. The rest compile cleanly.
For test 3, since a default is provided for B, I don't think it should be considered mandatory.
This is with TypeScript 1.6 beta. Please let me know if I'm doing something wrong.
Thanks, team!
-Steve O
interface AB { A: string; B?: string; } const childObject: AB = { A: "test" } const parentObject = { childObject }; function function1({childObject: {A, B = ""}}) { console.log(A); console.log(B); } function function2({childObject: {A, B = ""} = {A: "", B: ""}}) { console.log(A); console.log(B); } function function3({childObject: {A, B} = {A: "", B: ""}}) { console.log(A); console.log(B); } /* Test #1: Compiles cleanly */ function1(parentObject); /* Test #2: Gives expected error. Error: Argument of type '{}' is not assignable to parameter of type '{ childObject: { A: any; B?: string; }; }'. Property 'childObject' is missing in type '{}'. */ function1({}); /* Test #3: Not sure why this one is giving an error. A default is provided for B if the object exists, so technically B is not required. I would have only expected to see this error on Test #5 below. Argument of type '{ childObject: AB; }' is not assignable to parameter of type '{ childObject?: { A: string; B: string; }; }'. Types of property 'childObject' are incompatible. Type 'AB' is not assignable to type '{ A: string; B: string; }'. Property 'B' is optional in type 'AB' but required in type '{ A: string; B: string; }'. */ function2(parentObject); /* Test #4: Compiles cleanly */ function2({}); /* Test #5: Gives expected error. (Same as #3 but this one makes sense.) Argument of type '{ childObject: AB; }' is not assignable to parameter of type '{ childObject?: { A: string; B: string; }; }'. Types of property 'childObject' are incompatible. Type 'AB' is not assignable to type '{ A: string; B: string; }'. Property 'B' is optional in type 'AB' but required in type '{ A: string; B: string; }'. */ function3(parentObject); /* Test #6: Compiles cleanly */ function3({});
Metadata
Metadata
Assignees
Labels
DuplicateAn existing issue was already createdAn existing issue was already created