Skip to content

Commit b0d6d0d

Browse files
authored
Merge pull request microsoft#489 from Microsoft/fix13651
update generic extends example
2 parents 403f964 + 8de2829 commit b0d6d0d

File tree

1 file changed

+6
-9
lines changed

1 file changed

+6
-9
lines changed

pages/Generics.md

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -269,21 +269,18 @@ loggingIdentity({length: 10, value: 3});
269269
## Using Type Parameters in Generic Constraints
270270

271271
You can declare a type parameter that is constrained by another type parameter.
272-
For example, here we'd like to take two objects and copy properties from one to the other.
273-
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:
272+
For example, here we'd like to get a property from an object given its name.
273+
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:
274274

275275
```ts
276-
function copyFields<T extends U, U>(target: T, source: U): T {
277-
for (let id in source) {
278-
target[id] = source[id];
279-
}
280-
return target;
276+
function getProperty<T, K extends keyof T>(obj: T, key: K) {
277+
return obj[key];
281278
}
282279

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

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

289286
## Using Class Types in Generics

0 commit comments

Comments
 (0)