3 ms·
In my job I do a lot of code reviews and I notice that by using Typescript, devs tend to write worse JavaScript code. I often see that developers are assigning
by venfen 6y ago
In my job I do a lot of code reviews and I notice that by using Typescript, devs tend to write worse JavaScript code. I often see that developers are assigning `undefined` to properties in order to clean value or to satisfy badly written TS interface, instead of just using JS `delete` statement. Also a lot of times I see passing `undefined` to methods with optional params, instead of just skipping them. Here some bad practices:
If there is an interface: `interface ISomething { x?: string };` and obj of this interface to have `obj.x = undefined` instead of `delete obj.x`.
Writing methods: `function x(param0, param1?, param2?) {}` to be used as `x(1, undefined, '2');` instead of creating the func as `function x(param0, option: { param1?, param2? })` and using as `x(1, { param2: '2' })`.
Returning undefined from a function: `function x(): undefined { return undefined; }`, instead of `function x(): void { return; }`.
Mixing the meanings of `undefined` and `null`, can bring a lot of troubles for JS devs when they use `Object.keys` or using `arguments` in function. IMHO If we keep that `undefined` means missing while `null` means no value, then we will have better JS code, using: `'x' in obj` instead of `obj.x === undefined` or `typeof obj.x === 'undefined'`, `delete obj.x` instead of `obj.x = undefined`, `obj.x = null` and then `obj.x === null` instead of `obj.x == null`.
- Chyzwar 6y agoYou should probably never use delete. Not only it mutates objects but also have perf penalty. > If there is an interface: `interface ISomething { x?: string };` and obj of this interface to have `obj.x = undefined` instead of `delete obj.x`. In typescript additional properties are not a problem. Since it is using structural typing. In most cases spread and restructuring are better options for merging/overwriting and deleting. It is safer and easier to reason about. > Writing methods: `function x(param0, param1?, param2?) {}` to be used as `x(1, undefined, '2');` instead of creating the func as `function x(param0, option: { param1?, param2? })` and using as `x(1, { param2: '2' })`. I am not fan of creating functions taking options objects as argument. In many cases is better to create specialized functions