John Doe
John Doe

Reputation: 135

Understand Typescript Pick

My simplified code looks like this.

interface Todo {
  title: string;
  description: string;
  completed: boolean;
}
let a : Todo = {
  title: "title",
  description: "bla bla",
  completed: false
}

 type TodoPreview = Pick<Todo, "title" | "completed">;

 const todoPreview: TodoPreview = a ;
 console.log(todoPreview); // why todoPreview has  description property?

why todoPreview has description property?

Upvotes: 0

Views: 59

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074495

Because although it's type only has title and completed, the object itself has an additional property (description). todoPreview and a both point to the same object, which has title, description, and completed. The assignment todoPreview = a doesn't make a copy, it just points the todoPreview constant at the same object a points to.

In memory, you start out with:

                           +−−−−−−−−−−−−−−−−−−−−−−−−+
a:Ref55461−−−−−−−−−−−−−−−−>| (object)               |
                           +−−−−−−−−−−−−−−−−−−−−−−−−+
                           | title: "title"         |
                           | description: "bla bla" |
                           | completed: false       |
                           +−−−−−−−−−−−−−−−−−−−−−−−−+

Then after const todoPreview: TodoPreview = a; you have:

a:Ref55461−−−−−−−−−−−−−+
                       |
                       |   +−−−−−−−−−−−−−−−−−−−−−−−−+
                       +−−>| (object)               |
                       |   +−−−−−−−−−−−−−−−−−−−−−−−−+
                       |   | title: "title"         |
todoPreview:Ref55461−−−+   | description: "bla bla" |
                           | completed: false       |
                           +−−−−−−−−−−−−−−−−−−−−−−−−+

Even though you've given the const todoPreview the type TodoPreview, that doesn't affect the object itself.

Upvotes: 4

Related Questions