在打字稿中编写类型安全的“选择"函数 [英] Write a typesafe 'pick' function in typescript

查看:65
本文介绍了在打字稿中编写类型安全的“选择"函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

lodash具有选择功能,用法如下:

lodash has the pick function which is used as follows:

var object = { 'a': 1, 'b': '2', 'c': 3 };

_.pick(object, ['a', 'c']);
// => { 'a': 1, 'c': 3 }

我想在打字稿中写一个对此类型安全的版本.

I would like to write a type-safe version of this in typescript.

此功能的使用应为

pick(object, o => o.a, o.b)

我们的目标是不要两次指定相同的键,同时又要保护类型的安全性.

The goal is not to specify the same keys twice, and at the same time conserve type safety.

这有可能实现吗?

推荐答案

听起来像您正在寻找

Sounds like you might be looking for the Pick type. Would something like this work for you?

function pick<T, K extends keyof T>(obj: T, ...keys: K[]): Pick<T, K> {
  const ret: any = {};
  keys.forEach(key => {
    ret[key] = obj[key];
  })
  return ret;
}

const o = {a: 1, b: '2', c: 3}
const picked = pick(o, 'b', 'c');

picked.a; // not allowed
picked.b  // string
picked.c  // number

这篇关于在打字稿中编写类型安全的“选择"函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆