0

I have an array:

const names = [
    {
      id: 1,
      name: "one"
    },
    {
      id: 2,
      name: "two"
    }
  ];

then in jsx I have to call a function which is outside of the loop.

const renderSomething = (obj: any) => obj.name + " "; //obj type should not be any

How can I declare obj equal to objectOf names in typescript?

demo: https://codesandbox.io/s/react-typescript-forked-yvt0gj

3 Answers 3

1

You can define type for your object. For example:

type NameObject = {
  name: string;
  id: number;
};

export default function App() {
  const renderSomething = (obj: NameObject) => obj.name + " "; //obj should not be any

  const names: NameObject[] = [
    {
      id: 1,
      name: "one"
    },
    {
      id: 2,
      name: "two"
    }
  ];
  return <div className="App">{names.map((obj) => renderSomething(obj))}</div>;
}

Sign up to request clarification or add additional context in comments.

Comments

0

this is the lazy way for typing

import "./styles.css";

export default function App() {
  const names = [
    {
      id: 1,
      name: "one"
    },
    {
      id: 2,
      name: "two"
    }
  ];
  const renderSomething = (obj: typeof names[0]) => obj.name + " "; //obj should not be any
  return <div className="App">{names.map((obj) => renderSomething(obj))}</div>;
}

Comments

0
import "./styles.css";

interface IUser {
  id: number;
  name: string;
}
export default function App() {
  const names: IUser[] = [
    {
      id: 1,
      name: "one"
    },
    {
      id: 2,
      name: "two"
    }
  ];
  const renderSomething = (obj: IUser) => obj.name + " "; //obj should not be any
  return <div className="App">{names.map((obj) => renderSomething(obj))}</div>;
}

1 Comment

imagine you have huge arrays will you type them one by one?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.