打字稿:删除多个键循环数组

时间:2020-09-22 11:59:37

标签: typescript

我有一个对象

const person = {
  first: 'John',
  last: 'Doe',
  id: 1,
}

我想从人员对象中删除键。因此,在JavaScript中有效

['first', 'last'].forEach((i) => {
  delete person[i]
})

错误(来自未编译的VSCode编辑器)

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ first: string; last: string; id: number; }'.
  No index signature with a parameter of type 'string' was found on type '{ first: string; last: string; id: number; }'.ts(7053)

但是在TypeScript中显示错误。 TypeScript中的等效代码是什么。谢谢。

4 个答案:

答案 0 :(得分:2)

尝试一下:

const keysToDelete: (keyof typeof person)[] = ['first', 'last'] 

keysToDelete.forEach((i) => {
   delete person[i]
})

您需要让TS知道您仅使用person的键,而不仅仅是任意字符串

TS playground

答案 1 :(得分:1)

const person = {
  first: 'John',
  last: 'Doe',
  id: 1,
};


(['first', 'last'] as Array<keyof typeof person>).forEach((i) => {
  delete person[i]
})

您需要将forEach的i转换为人员对象的键类型。

答案 2 :(得分:1)

这对我也有用。

const person = {
  first: 'John',
  last: 'Doe',
  id: 1,
};


(['first', 'last']).forEach((i) => {
  delete person[i as keyof typeof person]
})

TypeScript Playground

但是这里的一个问题是它不验证密钥是否存在。因此,如果有人错误输入了错误的密钥,它将被忽略,例如

const person = {
  first: 'John',
  last: 'Doe',
  id: 1,
};


(['first', 'lasts']).forEach((i) => {
  delete person[i as keyof typeof person]
})

答案 3 :(得分:1)

使用keyof typeof person可行,但是有一种更简单的方法(因为TypeScript 3.4):使用const assertion

const person = {
  first: 'John',
  last: 'Doe',
  id: 1,
};

(['first', 'last'] as const).forEach(key => delete person[key]);

实际上,['first', 'last']的类型为string[],但as const的类型为readonly ["first", "last"],这是一个与{{1 }}对象。

我们还必须注意person对象的类型在删除后会更改的事实。现在是person,即Omit<typeof person, 'first' | 'last'>。我们还可以选择一种通用类型{ id: number }来指示{ id: number; first?: string; last?: string }first是可选字段。