skip to Main Content

I am getting this error to me and reading makes complete sense, but it makes no sense to me as to why I am getting it.

In the example below myOtherVariable is a string and variableName or so I thought… Am I missing something here?

Type '{ variableName: string; }' is not assignable to type 'string'

Here is how it is being called

const DynamicArea = (variableName: string) => (
   <div>Eventually this will be filled with some cool data</div>
);


export const myFunction = () => {
   const myOtherVariable = '';

   return (
       <DynamicArea variableName={myOtherVariable} />
   );
};

3

Answers


  1. The code bit (variableName: string) means nothing in Javascript.

    You are mixing up with typescript, where it means that your "variableName" is a string type.

    To fix it, in javascript you just re-write your component to be:

    const DynamicArea = (variableName) => (
       <div>Eventually this will be filled with some cool data</div>
    );
    

    There is no need to indicate what type your variable is in javascript.

    Login or Signup to reply.
  2. Try it like this by destructuring your props. Thats a common pitfall because you are typing the props object as a string but the props parameter is an object and you want to destructure a certain property out of it instead in your code:

    const DynamicArea = ({ variableName }: { variableName: string }) => (
        <div>Eventually this will be filled with some cool data</div>
    );
    

    As you see maybe now the error Type '{ variableName: string; }' is not assignable to type 'string' is indicating it that you are passing the component a { variableName: string } type but you declared it as string

    Login or Signup to reply.
  3. Ilja KO mentioned the simpler version and probably better for this scenario, but I want to add an alternative to the correct answer from Ilja.

    For TypeScript understand the prop types for the component, you can define its prop types explicitly as interface:

    interface DynamicAreaProps {
      variableName: string;
    }
    
    const DynamicArea: React.FC<DynamicAreaProps> = ({ variableName }) => (
      <div>Eventually this will be filled with some cool data</div>
    );
    
    export const myFunction = () => {
      const myOtherVariable = '';
    
      return (
        <DynamicArea variableName={myOtherVariable} />
      );
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search