Created
November 13, 2015 09:23
-
-
Save tomduncalf/fbae862b123445c117cb to your computer and use it in GitHub Desktop.
Function to emulate the ES7 destructuring with spread operator behaviour in Typescript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 | |
} |
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
Can you give a usage example?