Skip to content

Commit ace307c

Browse files
committed
Add Interfaces With The Same Name Are Merged as a TypeScript til
1 parent ad29a18 commit ace307c

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
1212

13-
_1184 TILs and counting..._
13+
_1185 TILs and counting..._
1414

1515
---
1616

@@ -1081,6 +1081,7 @@ _1184 TILs and counting..._
10811081

10821082
- [Add Types To An Object Destructuring](typescript/add-types-to-an-object-destructuring.md)
10831083
- [Compiler Checks For Unused Params And Variables](typescript/compiler-checks-for-unused-params-and-variables.md)
1084+
- [Interfaces With The Same Name Are Merged](typescript/interfaces-with-the-same-name-are-merged.md)
10841085
- [Re-Export An Imported Type](typescript/re-export-an-imported-type.md)
10851086
- [Type Narrowing With Similarly Shaped Objects](typescript/type-narrowing-with-similarly-shaped-objects.md)
10861087
- [Use An Array Check For Type Narrowing](typescript/use-an-array-check-for-type-narrowing.md)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Interfaces With The Same Name Are Merged
2+
3+
Here is the declartion of an interface in TypeScript.
4+
5+
```typescript
6+
interface Person {
7+
name: string
8+
}
9+
```
10+
11+
What if I were to add a separate interface declaration with the same name,
12+
`Person`?
13+
14+
```typescript
15+
interface Person {
16+
age: number
17+
}
18+
```
19+
20+
TypeScript performs declaration merging. So the types of the two interfaces
21+
would be combined. So, a variable of type `Person` can have an `name` and an
22+
`age`.
23+
24+
```typescript
25+
const person: Person = {
26+
age: 22,
27+
name: 'Bob'
28+
}
29+
```
30+
31+
See a [live
32+
example](https://www.typescriptlang.org/play?ssl=12&ssc=2&pln=5&pc=1#code/JYOwLgpgTgZghgYwgAgArQM4HsTIN4BQyxyIcAthAFzIZhSgDmBAvgQaJLIiulNrkIlkcRtVIBXcgCNordghx1kAB0w4afAcgC8+IiVHiATMYA0B4mUo0A5ACEs02-IJr+OAHRGgA)
33+
in the TS Playground.
34+
35+
This is different from how object type declarations handle it. If I were to try
36+
to define two separate `type`s with the same name, that would result in a type
37+
error.
38+
39+
[source](https://www.typescriptlang.org/docs/handbook/declaration-merging.html#merging-interfaces)

0 commit comments

Comments
 (0)