Hacker News new | ask | show | jobs
by nawgz 1270 days ago
> Why not enforce object types?

It would be incredibly painful to write idiomatic JS with constant narrowing required and would lead to huge performance issues.

Imagine you write some generic sort capabilities, sorting by label, createdDate, etc., and then you declare some types

    interface SortableByLabel { label: string }
    interface SortableByCreatedDate { createdDate: Date }
    ...
Then you implement a method

    function sortByLabel(a: SortableByLabel, b: SortableByLabel) { ... }
I've written enough, I think you can see how easily this works today and how painful and un-performant it would be to do this if you had to narrow your objects or constantly write extra info into your types to allow them to not enforce narrowing, and then there's a whole can of worms around your "widen"-able object types being illegal to functions that require exact types, ...

Instead you can just write arrays...

    interface MyInterface {
      key1: Type1;
      key2: Type2;
      ...
    }

    const myKeys:Array<keyof MyInterface> = [
      'key1',
      'key2',
      ...
    ] as const;

    function operatesOnKeys(object: MyInterface) {
      // don't use Object.entries...
      myKeys.forEach((key) => {
        object[key];
        // TS is happy, and bonus:
        // this will be type checked later if MyInterface changes
      });
    }
I think TS has some issues but this isn't one of them.