Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1287,3 +1287,17 @@ export async function asyncSome<T>(
export function isDefined<T>(value: T | null | undefined): value is T {
return value !== undefined && value !== null;
}

/** Like `Object.keys`, but infers the correct key type. */
export function keysTyped<T extends Record<string, any>>(
object: T,
): Array<keyof T> {
return Object.keys(object) as Array<keyof T>;
}

/** Like `Object.entries`, but infers the correct key type. */
export function entriesTyped<T extends Record<string, any>>(
object: T,
): Array<[keyof T, NonNullable<T[keyof T]>]> {
return Object.entries(object) as Array<[keyof T, NonNullable<T[keyof T]>]>;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The NonNullable<T[keyof T]> is an undocumented refinement that is unsound.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right. I have been thinking about this a good bit yesterday and I am not entirely sure about the best solution.

I initially thought that maybe using Exclude<T[keyof T], undefined> instead would be better, but then remembered that we can explicitly set a key to undefined in which case Object.entries still returns a pair for the key and undefined as the value.

I am now thinking that perhaps it would be better to explicitly filter the results of these functions to exclude undefined values and keys that don't belong to T?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd like the naming / docstring to be different here for both keysTyped and entriesTyped. Perhaps something with strict/exact/...? And definitely not something with "correct", since the builtin Object.keys is actually the one that is correct already.
See https://stackoverflow.com/questions/55012174/why-doesnt-object-keys-return-a-keyof-type-in-typescript

}