From eaec600dd29f42f9f7a9fd7b87dafd3260bb0ec9 Mon Sep 17 00:00:00 2001 From: Matt Pocock Date: Mon, 20 Feb 2023 15:24:54 +0000 Subject: [PATCH] Added note to the readme --- readme.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/readme.md b/readme.md index 9fad688..9865f8e 100644 --- a/readme.md +++ b/readme.md @@ -279,3 +279,29 @@ const func: Func = () => { ``` So, the only reasonable type for `Object.keys` to return is `Array`. + +### Generics for `JSON.parse`, `Response.json` etc + +A common request is for `ts-reset` to add type arguments to functions like `JSON.parse`: + +```ts +const str = JSON.parse('"hello"'); + +console.log(str); // string +``` + +This appears to improve the DX by giving you autocomplete on the thing that gets returned from `JSON.parse`. + +However, we argue that this is a lie to the compiler and so, unsafe. + +`JSON.parse` and `fetch` represent _validation boundaries_ - places where unknown data can enter your application code. + +If you _really_ know what data is coming back from a `JSON.parse`, then an `as` assertion feels like the right call: + +```ts +const str = JSON.parse('"hello"') as string; + +console.log(str); // string +``` + +This provides the types you intend and also signals to the developer that this is _slightly_ unsafe.