TypeScript 2.1 now supports object spread/rest, so no workarounds are needed anymore!
TypeScript s
You probably can't avoid creating a new object with a subset of the properties of this.props
, but you can do that with type safety.
For example:
interface LinkProps {
textToDisplay: string;
}
const LinkPropsKeys: LinkProps = { textToDisplay: "" };
class Link extends React.Component {
public render(): JSX.Element {
return (
{ this.props.textToDisplay }
);
}
private getHtmlProps(): React.HTMLAttributes {
let htmlProps = {} as React.HTMLAttributes;
for (let key in this.props) {
if (!(LinkPropsKeys as any)[key]) {
htmlProps[key] = this.props[key];
}
}
return htmlProps;
}
}
Using LinkPropsKeys
object, which needs to match the LinkProps
, will help you keep the keys between the interface and the runtime lookup synchronized.