Skip to content

Commit 55ba1b4

Browse files
committed
intersection types
closes #22
1 parent 5932369 commit 55ba1b4

File tree

1 file changed

+24
-2
lines changed

1 file changed

+24
-2
lines changed

Diff for: docs/types/type-system.md

+24-2
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,30 @@ function formatCommandline(command: string[]|string) {
213213
}
214214
```
215215

216+
## Intersection Types
217+
`extend` is a very common pattern in JavaScript where you take two objects and create a new one that has the features of both these objects. An **Intersection Type** allows you to use this pattern in a safe way as demonstrated below:
218+
219+
```ts
220+
function extend<T, U>(first: T, second: U): T & U {
221+
let result = <T & U> {};
222+
for (let id in first) {
223+
result[id] = first[id];
224+
}
225+
for (let id in second) {
226+
if (!result.hasOwnProperty(id)) {
227+
result[id] = second[id];
228+
}
229+
}
230+
return result;
231+
}
232+
233+
var x = extend({ a: "hello" }, { b: 42 });
234+
235+
// x now has both `a` and `b`
236+
var a = x.a;
237+
var b = x.b;
238+
```
239+
216240
## Tuple Type
217241
JavaScript doesn't have first class tuple support. People generally just use an array as a tuple. This is exactly what the TypeScript type system supports. Tuples can be annotated using `:[typeofmember1, typeofmember2]` etc. A tuple can have any number of members. Tuples are demonstrated in the below example:
218242

@@ -262,5 +286,3 @@ type Callback = (data: string) => void;
262286
263287
## Summary
264288
Now that you can start annotating most of your JavaScript code we can jump into the nitty gritty details of all the power available in the TypeScript's Type System.
265-
266-

0 commit comments

Comments
 (0)