如何在TypeScript中实现弹拨功能? [英] How to implement a pluck function in TypeScript?

查看:62
本文介绍了如何在TypeScript中实现弹拨功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常需要从对象中拔出属性

I often need to pluck properties out of an object

const obj = {a:1, b: 2, c: 3};
const plucked = pluck(obj, 'a', 'b'); // {a: 1, b:2}

但是,如果要使用类型安全性,则在TypeScript中不容易做到这一点,因为我无法在TypeScript中实现具有以下签名的函数,而我在

However, this is not easy to do in TypeScript if you want type safety because I can't implement a function with the following signature in TypeScript, which I found on TypeScript's manual.

declare function pick<T, K extends keyof T>(obj: T, ...keys: K[]): Pick<T, K>;

我无法获得已编译的版本,这是我尝试过的版本:

I couldn't get a version that compiled, here's a version I tried:

function pluck<T, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> {
    // Type '{}' is not assignable to type 'Pick<T, K>'.
    const ret: Pick<T, K> = {};
    for (let key of keys) { 
        ret[key] = obj[key];
    }
    return ret; 
}

这是否意味着我需要使用环境声明并在JS中声明该函数?

Does this mean I need to use ambient declarations and declare the function in JS?

推荐答案

我最终在我操作的对象上使用了any,并且TypeScript很高兴允许它作为返回值.

I ended up using any on the object that I manipulate and TypeScript is happy allowing that as a return value. See it in action

function pluck<T, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> {
    const ret: any = {};
    for (let key of keys) { 
        ret[key] = obj[key];
    }
    return ret; 
}

const less = pluck({ a: 1, b: '2', c: true }, ['a', 'c']);

这篇关于如何在TypeScript中实现弹拨功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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