Skip to content

Commit 7cd355c

Browse files
committed
add new type extraction tip
1 parent abefd64 commit 7cd355c

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

README.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1404,6 +1404,39 @@ function foo(bar: string) {
14041404
type FooReturn = ReturnType<typeof foo>; // { baz: number }
14051405
```
14061406
1407+
In fact you can grab virtually anything public: [see this blogpost from Ivan Koshelev](http://ikoshelev.azurewebsites.net/search/id/11/Pragmatic-uses-of-TypeScript-type-system-My-type-of-type)
1408+
1409+
```ts
1410+
function foo() {
1411+
return {
1412+
a: 1,
1413+
b: 2,
1414+
subInstArr: [{
1415+
c: 3,
1416+
d: 4
1417+
}]
1418+
}
1419+
}
1420+
1421+
type InstType = ReturnType<typeof foo>
1422+
type SubInstArr = InstType['subInstArr'];
1423+
type SubIsntType = SubInstArr[0];
1424+
1425+
let baz: SubIsntType = {
1426+
c: 5,
1427+
d: 6 // type checks ok!
1428+
}
1429+
1430+
//You could just write a one-liner,
1431+
//But please make sure it is forward-readable
1432+
//(you can understand it from reading once left-to-right with no jumps)
1433+
type SubIsntType2 = ReturnType<typeof foo>['subInstArr'][0];
1434+
let baz2: SubIsntType2 = {
1435+
c: 5,
1436+
d: 6 // type checks ok!
1437+
}
1438+
```
1439+
14071440
# Troubleshooting Handbook: Images and other non-TS/TSX files
14081441
14091442
Use [declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html):

0 commit comments

Comments
 (0)