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>: Guaranteesobjis an object with string keys (values are typed asunknown, which you can narrow further if your use case requires it)K extends keyof T: Restrictspropto only be valid keys of the input objectT—so TypeScript will throw an error if you try to pass a property that doesn't exist onobjOmit<T, K>: The return type is exactly the type ofTminus the propertyK, so TypeScript infers the correct shape for the returned object automatically
This resolves both issues:
- The TSLint error disappears because
Tnow has a clear index signature viaRecord<string, unknown> - The
resultvariable 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

