Home > Software engineering >  objectOf of array of object in typescript?
objectOf of array of object in typescript?

Time:03-04

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

CodePudding user response:

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>;
}

CodePudding user response:

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>;
}

CodePudding user response:

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>;
}
  • Related