TypeScript 2:从 2-field 对象中删除项目 [英] TypeScript 2: Remove item from 2-field object

查看:17
本文介绍了TypeScript 2:从 2-field 对象中删除项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的 2-field 对象

I have a 2-field object like this

{ id: number, name: string }

...并且想要删除 name 项.

...and want to remove the name item.

我如何在 TypeScript 中实现这一点?我试过使用过滤器、删除等,但我得到的只是

How do I accomplish that in TypeScript? I've tried using filter, delete etc but all I get is

TS2339: Property 'filter' does not exist on type '{}'.

我认为这与这个问题有关 什么是type '{}'"?但我需要帮助才能弄清楚.

I think this relates to this question What is "type '{}'"? but I need help to figure it out.

推荐答案

考虑:

let x : { id: number, name?: string } = {id: 1, name: 'foo'};

你可以简单地使用删除:

You can simply use delete:

delete x.name;
console.log(x); // {id: 1}

这篇关于TypeScript 2:从 2-field 对象中删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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