TypeScript workaround for rest props in React

前端 未结 6 771
迷失自我
迷失自我 2021-02-06 22:50

Updated for TypeScript 2.1

TypeScript 2.1 now supports object spread/rest, so no workarounds are needed anymore!


Original Question

TypeScript s

6条回答
  •  情书的邮戳
    2021-02-06 23:15

    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.

提交回复
热议问题