1

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) ?

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

5 Comments

I have 2 lint errors Cannot find name 'Omit' and Rest types may only be created from object types . Being I am on TypeScript 3.1 I understand the Omit error but not the second error
@MouadEnnaciri both of those errors happen because you are in 3.1 the latest version is 3.5 and the code works with that. I can provide a backward compatible version but it can't use spread to remove the property. Correctly typing spread on generic types happened in 3.2
I understand, that it is the version compatible the v3.1?
@MouadEnnaciri i added a version for 3.1. All ts releases are mostly compatible, but they all also have a number of breaking changes, upgrading might yield new errors as the type system becomes stricter in newer versions. Although if it compiles I expect it to work as it did before.
I would like to avoid the delete operator but I mark the question as resolved being the limitation caused by my TS version. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.