diff --git a/README.md b/README.md index af4be95..926bb8a 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1184 TILs and counting..._ +_1185 TILs and counting..._ --- @@ -1081,6 +1081,7 @@ _1184 TILs and counting..._ - [Add Types To An Object Destructuring](typescript/add-types-to-an-object-destructuring.md) - [Compiler Checks For Unused Params And Variables](typescript/compiler-checks-for-unused-params-and-variables.md) +- [Interfaces With The Same Name Are Merged](typescript/interfaces-with-the-same-name-are-merged.md) - [Re-Export An Imported Type](typescript/re-export-an-imported-type.md) - [Type Narrowing With Similarly Shaped Objects](typescript/type-narrowing-with-similarly-shaped-objects.md) - [Use An Array Check For Type Narrowing](typescript/use-an-array-check-for-type-narrowing.md) diff --git a/typescript/interfaces-with-the-same-name-are-merged.md b/typescript/interfaces-with-the-same-name-are-merged.md new file mode 100644 index 0000000..f6124a0 --- /dev/null +++ b/typescript/interfaces-with-the-same-name-are-merged.md @@ -0,0 +1,39 @@ +# Interfaces With The Same Name Are Merged + +Here is the declartion of an interface in TypeScript. + +```typescript +interface Person { + name: string +} +``` + +What if I were to add a separate interface declaration with the same name, +`Person`? + +```typescript +interface Person { + age: number +} +``` + +TypeScript performs declaration merging. So the types of the two interfaces +would be combined. So, a variable of type `Person` can have an `name` and an +`age`. + +```typescript +const person: Person = { + age: 22, + name: 'Bob' +} +``` + +See a [live +example](https://www.typescriptlang.org/play?ssl=12&ssc=2&pln=5&pc=1#code/JYOwLgpgTgZghgYwgAgArQM4HsTIN4BQyxyIcAthAFzIZhSgDmBAvgQaJLIiulNrkIlkcRtVIBXcgCNordghx1kAB0w4afAcgC8+IiVHiATMYA0B4mUo0A5ACEs02-IJr+OAHRGgA) +in the TS Playground. + +This is different from how object type declarations handle it. If I were to try +to define two separate `type`s with the same name, that would result in a type +error. + +[source](https://www.typescriptlang.org/docs/handbook/declaration-merging.html#merging-interfaces)