Reputation: 1269
I have a JavaScript helper function which allows to remove a property of an object :
removeProp(obj, prop) {
const { [prop]: _, ...result } = obj;
return result;
}
TypeScript version :
removeProp(obj: Object, prop: string): Object {
// tslint:disable-next-line: no-shadowed-variable
const { [prop]: _, ...result } = obj;
return result;
}
1- I have a lint error : type 'Object' has no index signature corresponding to type 'string' tslint
in [prop]
.
2- How i can initialize result
variable with the right type if obj
is a generic (takes all properties of the generic type - the removed property) ?
Upvotes: 1
Views: 79
Reputation: 249706
You need to make the function generic, with a generic parameter (lets call in T
) to represent the type of the object and a second parameter (lets call it K
) that should be a keyof T
. For the return type you can use Omit<T, K>
which will remove a key from a given type (although strictly speaking you can leave the return type blank and it will be correctly inferred)
function removeProp<T, K extends keyof T>(obj: T, prop: K): Omit<T, K> {
const { [prop]: _, ...result } = obj;
return result;
}
let o = removeProp({ a: 1, b: 2}, "b")
A version that works on 3.1 can't use spread (as spread with generic type parameters is not supported in that version, that was allowed in 3.2) and has to define Omit
as that did not exist in 3.1 either (added in 3.5)
type Omit<T, K extends PropertyKey> = Pick<T, Exclude<keyof T, K>>
function removeProp<T, K extends keyof T>(obj: T, prop: K): Omit<T, K> {
const result = Object.assign({}, obj);
delete result[prop]
return result;
}
let o = removeProp({ a: 1, b: 2}, "b");
console.log(o);
Upvotes: 2