total-typescript / ts-reset

A 'CSS reset' for TypeScript, improving types for common JavaScript API's
https://www.totaltypescript.com/ts-reset
MIT License
7.74k stars 117 forks source link

Better Object.entries #167

Closed PCOffline closed 10 months ago

PCOffline commented 10 months ago

Intro

This type changes the behaviour of Object.entries to return more specific types:

Object.entries({ a: 1, b: 2, c: 3 } as const);
// Before change: [string, 1 | 2 | 3][]
// After change: (["a", 1] | ["b", 2] | ["c", 3])[]

Object.entries({ a: true, b: 'string', c: { field: 1 } } as const);
// Before change: [string, true | "string" | { readonly field: 1; }][]
// After change: (["a", true] | ["b", "string"] | ["c", { readonly field: 1; }])[]

Object.entries([1, 2, 3] as const);
// Before change: [string, 1 | 2 | 3][]
// After change: [number, 2 | 1 | 3][]

Caveats

PCOffline commented 10 months ago

Todo: update readme

mattpocock commented 10 months ago

Please read the section in the readme that describes why we won't make this change.

PCOffline commented 10 months ago

Alright, didn't see it in the GitHub Readme. Makes sense though

tyilo commented 7 months ago

Please read the section in the readme that describes why we won't make this change.

@mattpocock This seems to be gone from the README. Could you add the note here?

tyilo commented 7 months ago

Found it:

Rules we won't add

Object.keys/Object.entries

A common ask is to provide 'better' typings for Object.keys, so that it returns Array<keyof T> instead of Array<string>. Same for Object.entries. ts-reset won't be including rules to change this.

TypeScript is a structural typing system. One of the effects of this is that TypeScript can't always guarantee that your object types don't contain excess properties:

type Func = () => {
  id: string;
};

const func: Func = () => {
  return {
    id: "123",
    // No error on an excess property!
    name: "Hello!",
  };
};

So, the only reasonable type for Object.keys to return is Array<string>.

PCOffline commented 7 months ago

Bruh this issue was closed 3 months ago how'd you even find it