Skip to content

Function: pick()

Call Signature

ts
function pick<T, K>(obj, keys): Pick<T, K>;

Creates a new object with only the specified properties from the source object. 从源对象中创建一个只包含指定属性的新对象。

This function is useful for extracting specific properties from an object, creating a subset with only the properties you need. 此函数对于从对象中提取特定属性很有用, 创建一个只包含所需属性的子集。

Type Parameters

Type ParameterDescription
TThe type of the source object / 源对象的类型
K extends string | number | symbolThe keys to pick from the object / 要从对象中选择的键

Parameters

ParameterTypeDescription
objTThe source object / 源对象
keysreadonly K[]The property keys to pick / 要选择的属性键

Returns

Pick<T, K>

A new object with only the picked properties / 只包含选择属性的新对象

Example

typescript
const user = { id: 1, name: 'John', email: 'john@example.com', password: 'secret' }
pick(user, ['id', 'name', 'email'])
// => { id: 1, name: 'John', email: 'john@example.com' }

pick(user, [])
// => {}

Since

1.0.0

Call Signature

ts
function pick<T, K>(obj, ...keys): Pick<T, K>;

Creates a new object with only the specified properties from the source object. 从源对象中创建一个只包含指定属性的新对象。

This function is useful for extracting specific properties from an object, creating a subset with only the properties you need. 此函数对于从对象中提取特定属性很有用, 创建一个只包含所需属性的子集。

Type Parameters

Type ParameterDescription
TThe type of the source object / 源对象的类型
K extends string | number | symbolThe keys to pick from the object / 要从对象中选择的键

Parameters

ParameterTypeDescription
objTThe source object / 源对象
...keysK[]The property keys to pick / 要选择的属性键

Returns

Pick<T, K>

A new object with only the picked properties / 只包含选择属性的新对象

Example

typescript
const user = { id: 1, name: 'John', email: 'john@example.com', password: 'secret' }
pick(user, ['id', 'name', 'email'])
// => { id: 1, name: 'John', email: 'john@example.com' }

pick(user, [])
// => {}

Since

1.0.0

Released under the MIT License.