Skip to content

Commit

Permalink
feat(utils): 新增 pickAll
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Jul 31, 2023
1 parent 5ff1690 commit 07ee03e
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ export * from './onceMeanwhile'
export * from './parseDataUrl'
export * from './parseUrlQueryString'
export * from './pascalCase'
export * from './pickAll'
export * from './pickStrict'
export * from './placeKitten'
export * from './pMap'
Expand Down
37 changes: 37 additions & 0 deletions src/utils/pickAll.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { pickAll } from './pickAll'

describe('pickAll', () => {
test('ok', () => {
const data: {
id: number
name: string
} = {
id: 1,
name: 'jack',
}
// @ts-expect-error
data.gender = 1
expect(pickAll(data, ['id', 'name'])).toEqual({
id: 1,
name: 'jack',
})
expect(pickAll(data, ['name', 'id'])).toEqual({
id: 1,
name: 'jack',
})
// @ts-expect-error
expect(pickAll(data, ['name'])).toEqual({
name: 'jack',
})
expect(pickAll(data, ['name', 'id', 'id'])).toEqual({
id: 1,
name: 'jack',
})
// @ts-expect-error
expect(pickAll(data, ['id', 'name', 'gender'])).toEqual({
id: 1,
name: 'jack',
gender: 1,
})
})
})
40 changes: 40 additions & 0 deletions src/utils/pickAll.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { pick } from 'lodash-uni'

// https://github.com/sindresorhus/type-fest/issues/656
type IsEqual<A, B> = (<G>() => G extends A ? 1 : 2) extends <G>() => G extends B
? 1
: 2
? true
: false
type TupleToUnion<ArrayType> = ArrayType extends readonly unknown[]
? ArrayType[number]
: never
type TupleOf<Tuple extends ReadonlyArray<Values>, Values> = IsEqual<
Values,
TupleToUnion<Tuple>
> extends true
? Tuple
: never

// 过于卡顿
// https://github.com/microsoft/TypeScript/issues/13298#issuecomment-692864087
// type TupleUnion<U extends string, R extends string[] = []> = {
// [S in U]: Exclude<U, S> extends never
// ? [...R, S]
// : TupleUnion<Exclude<U, S>, [...R, S]>
// }[U] &
// string[]

/**
* 选中对象中的所有类型上可见的属性并返回。
*
* @param data 对象
* @param keys 属性列表
*/
export function pickAll<
T extends Record<string, any>,
K extends keyof T,
Tuple extends ReadonlyArray<K>,
>(data: T, keys: TupleOf<Tuple, K>): T {
return pick(data, keys as any) as any
}

0 comments on commit 07ee03e

Please sign in to comment.