You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/types/generics.md
+36Lines changed: 36 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -176,3 +176,39 @@ This is just an example, if you are considering on using this `require` typings
176
176
177
177
1. It's already there in `node.d.ts` you can install using `npm install @types/node --save-dev`.
178
178
1. You should consider using the type definitions for your library e.g. for jquery `npm install @types/jquery --save-dev` instead of using raw `require`.
179
+
180
+
### Caveat: Use generics to make it easier to annotate
181
+
182
+
The previous example of `require<T>` was intentionally meant to make clear the fact that generics used *only once* are no better than an assertion in terms of type safety. That said they do provide *convenience* to your API.
183
+
184
+
An example is a function that loads a json response. It returns a promise of *whatever type you pass in*:
185
+
```ts
186
+
const getJSON = <T>(config: {
187
+
url:string,
188
+
headers?: { [key:string]:string },
189
+
}):Promise<T> => {
190
+
const fetchConfig = ({
191
+
method: 'GET',
192
+
'Accept': 'application/json',
193
+
'Content-Type': 'application/json',
194
+
...(config.headers|| {})
195
+
});
196
+
returnfetch(config.url, fetchConfig)
197
+
.then<T>(response=>response.json());
198
+
}
199
+
```
200
+
Note that you still have to explicitly annotate what you want, but the `getJSON<T>` signature `(config) => Promise<T>` saves you a few key strokes:
0 commit comments