You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript迁移:移除对象属性函数的TSlint错误与泛型类型问题

Hey there! Let's tackle these TypeScript issues one by one to get your removeProp function working smoothly.

Fixing the TSLint "no index signature" error

The root of this error is that you're using the generic Object type, which TypeScript treats as an overly broad, non-specific type without an index signature. When you try to destructure [prop] from it, TypeScript can't confirm the object actually supports string-based key access.

To fix this, we need to type obj as a more specific object type that explicitly allows string keys. We can use a generic T constrained to extend Record<string, unknown> (this is safer than any because it maintains type checking while allowing flexible object shapes).

Making the return type correctly omit the specified property

For the second problem, TypeScript has a built-in utility type called Omit<T, K> that does exactly what we need: it takes a type T and removes the properties listed in K. We just need to ensure our prop parameter is constrained to be a valid key of the input object T, so TypeScript knows we're only passing valid property names.

Here's the revised, fully typed version of your function:

function removeProp<T extends Record<string, unknown>, K extends keyof T>(obj: T, prop: K): Omit<T, K> {
  const { [prop]: _, ...result } = obj;
  return result;
}

Let's break this down:

  • T extends Record<string, unknown>: Guarantees obj is an object with string keys (values are typed as unknown, which you can narrow further if your use case requires it)
  • K extends keyof T: Restricts prop to only be valid keys of the input object T—so TypeScript will throw an error if you try to pass a property that doesn't exist on obj
  • Omit<T, K>: The return type is exactly the type of T minus the property K, so TypeScript infers the correct shape for the returned object automatically

This resolves both issues:

  1. The TSLint error disappears because T now has a clear index signature via Record<string, unknown>
  2. The result variable gets the correct type (Omit<T, K>) without extra initialization work, as TypeScript infers it from the destructuring and return type annotation

Let's test it with an example to see the type inference in action:

const user = { name: "Alice", age: 30, email: "alice@example.com" };
const userWithoutAge = removeProp(user, "age");
// userWithoutAge is correctly typed as { name: string; email: string }

Now TypeScript will enforce valid property inputs, and the returned object's type will accurately reflect the removed property.

内容的提问来源于stack exchange,提问作者Mouad Ennaciri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 09:08:42