microsoft / vscode

Visual Studio Code
https://code.visualstudio.com
MIT License
162.47k stars 28.64k forks source link

Fix unsafe type assertions on object literals #211878

Open mjbvz opened 4 months ago

mjbvz commented 4 months ago

<T>{ ... } style type assertions are unsafe as they can hide some common typing errors such as missing properties on the object. This has caused errors for me multiple times now, so I think it would be good to make a pass through the code

Fixing

I've added a new eslint rule for this called local/code-no-dangerous-type-assertions. You can turn it on in .eslintrc.json

In most cases, we should prefer using proper typings such as:

const x = <T>{...};

// Becomes --->

const x: T = {...};
arr.map(x => <T>{ ... })

// Becomes --->

arr.map((x): T => ({ ... }));

If you want to make sure an object fulfills a certain type, prefer using the satisfies operator instead which will enforce the type without actually changing its shape:

const x = <T>{...};

// Becomes --->

const x = {...} satisfies T;

Note that this rule still allows <any> casts for now. You can also suppress this rule in the few cases where you need to workaround it using an eslint comment


Tracking

alexr00 commented 4 months ago

I think I got all mine ✅

connor4312 commented 4 months ago

I got rid of mine, but I had to add a new cast via a mapValues function in common/objects.ts -- still better to keep the unsafeness hidden inside well-defined functions.