Skip to content

Instantly share code, notes, and snippets.

@tomduncalf
Created November 13, 2015 09:23
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomduncalf/fbae862b123445c117cb to your computer and use it in GitHub Desktop.
Save tomduncalf/fbae862b123445c117cb to your computer and use it in GitHub Desktop.
Function to emulate the ES7 destructuring with spread operator behaviour in Typescript
/**
* Return a copy of `obj` with the specified properties removed
* Modified from Babel source code
*/
function objectWithoutProperties (obj: Object, keys: string[]): any {
let target = {}
for (var i in obj) {
if (keys.indexOf(i) >= 0) { continue }
if (!Object.prototype.hasOwnProperty.call(obj, i)) { continue }
target[i] = obj[i];
}
return target;
}
/**
* Function to emulate the ES7 destructuring with spread operator behaviour, commonly used with Redux.
* Returns a copy of `obj` with the properties specified in `keys` copied over,
* and all remaining properties inside an object in a property called `__rest`.
*
* Example:
* ES7 code: const { value, onChange, onBlur, ...props } = this.props
* ES6 with this: const { value, onChange, onBlur, __rest: props } = destructure(this.props, ['value', 'onChange', 'onBlur'])
*
* TODO deprecate this when tsc supports the ES7 operator: https://github.com/Microsoft/TypeScript/issues/2103
*/
export function destructure(obj: Object, keys: string[]): any {
let destructured: any = {}
// Map all the properties in keys on to the new object
for (let key of keys) {
destructured[key] = obj[key]
}
// And then get the left over properties and assign to "__rest"
destructured.__rest = objectWithoutProperties(obj, keys)
return destructured
}
@amcdnl
Copy link

amcdnl commented Jan 26, 2016

Can you give a usage example?

@vyorkin
Copy link

vyorkin commented Jun 19, 2016

@amcdnl

const { value, onChange, onBlur, __rest: props } = destructure(this.props, ['value', 'onChange', 'onBlur'])

not so perfect :) I'll wait

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment