TypeScript workaround for rest props in React

前端 未结 6 776
迷失自我
迷失自我 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:10

    I've accepted Nitzen Tomer's answer because it was the basic idea I was going for.

    As a more generalized solution this is what I ended up going with:

    export function rest(object: any, remove: {[key: string]: any}) {
      let rest = Object.assign({}, object);
      Object.keys(remove).forEach(key => delete rest[key]);
      return rest;
    }
    

    So I can use it like this:

    const {a, b, c} = props;
    const htmlProps = rest(props, {a, b, c});
    

    And once TypeScript supports object rest/spread I can just look for all usages of rest() and simplify it to const {a, b, c, ...htmlProps} = props.

提交回复
热议问题