Skip to content

Instantly share code, notes, and snippets.

@sashuk
Last active January 29, 2024 18:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sashuk/1663acfcfdc1a0300490b7ce1d753da0 to your computer and use it in GitHub Desktop.
Save sashuk/1663acfcfdc1a0300490b7ce1d753da0 to your computer and use it in GitHub Desktop.
spread-operator-and-type-checks-in-typescript.md

Problem

Spread operator in TypeScript is not properly type checked.

Reasoning – https://stackoverflow.com/a/53405628/1860213

Examples

TypeScript example

type SomeType = {
  a: string
}

const foo = ({ a }: SomeType) => {
  console.log(a)
}

const bar = (input: SomeType) => {
    // Case 1 – no type error
    const localSpread = {
        ...input,
        c: 'test'
    }

    foo(localSpread)

    // Case 2 – no type error
    const localInput = {
        a: input.a,
        b: 'test'
    }

    foo(localInput)

    // Case 3 – type error
    foo({
        a: input.a,
        b: 'test'
    })
}

TypeScript + React example

type SomeProps = {
  a: string;
};

const SomeComponent = (props: SomeProps) => <div />;

export default function App() {
  // Case 1 - no type error
  const someComponentInputs = {
    a: "a",
    b: "b",
  };

  //return (<div><SomeComponent {...someComponentInputs} /></div>);

  // Case 2 – throws TypeScript error "Property 'b' does not exist on type "
  return (
    <div>
      <SomeComponent a="a" b="b" />
    </div>
  );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment