looser pick

works better with object unions
This commit is contained in:
MapleLeaf
2021-12-29 01:50:52 -06:00
parent b155cfd526
commit 4fe5dd2cf9
2 changed files with 12 additions and 4 deletions

View File

@@ -1,11 +1,13 @@
import type { LoosePick, UnknownRecord } from "./types"
// eslint-disable-next-line import/no-unused-modules // eslint-disable-next-line import/no-unused-modules
export function pick<T, K extends keyof T>( export function pick<T, K extends keyof T | PropertyKey>(
object: T, object: T,
...keys: K[] keys: K[],
): Pick<T, K> { ): LoosePick<T, K> {
const result: any = {} const result: any = {}
for (const key of keys) { for (const key of keys) {
const value = object[key] const value = (object as UnknownRecord)[key]
if (value !== undefined) { if (value !== undefined) {
result[key] = value result[key] = value
} }

View File

@@ -4,3 +4,9 @@ export type MaybePromise<T> = T | Promise<T>
export type ValueOf<Type> = Type extends ReadonlyArray<infer Value> export type ValueOf<Type> = Type extends ReadonlyArray<infer Value>
? Value ? Value
: Type[keyof Type] : Type[keyof Type]
export type UnknownRecord = Record<PropertyKey, unknown>
export type LoosePick<Shape, Keys extends PropertyKey> = {
[Key in Keys]: Shape extends Record<Key, infer Value> ? Value : never
}