Skip to content
This repository was archived by the owner on Oct 12, 2022. It is now read-only.

update generic extends example #489

Merged
merged 3 commits into from
Feb 9, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 6 additions & 9 deletions pages/Generics.md
Original file line number Diff line number Diff line change
Expand Up @@ -269,21 +269,18 @@ loggingIdentity({length: 10, value: 3});
## Using Type Parameters in Generic Constraints

You can declare a type parameter that is constrained by another type parameter.
For example, here we'd like to take two objects and copy properties from one to the other.
We'd like to ensure that we're not accidentally writing any extra properties from our `source`, so we'll place a constraint between the two types:
For example, here we'd like to get a property from an object given its name.
We'd like to ensure that we're not accidentally grabbing a property that does not exist on the `obj`, so we'll place a constraint between the two types:

```ts
function copyFields<T extends U, U>(target: T, source: U): T {
for (let id in source) {
target[id] = source[id];
}
return target;
function getProperty<T, K extends keyof T>(obj: T, key: K) {
return obj[key];
}

let x = { a: 1, b: 2, c: 3, d: 4 };

copyFields(x, { b: 10, d: 20 }); // okay
copyFields(x, { Q: 90 }); // error: property 'Q' isn't declared in 'x'.
getProperty(x, "a"); // okay
getProperty(x, "m"); // error: Argument of type 'm' isn't assignable to 'a' | 'b' | 'c' | 'd'.
```

## Using Class Types in Generics
Expand Down