DavidDai
DavidDai

Reputation: 21

How to get the array object type in typescript

For example I have an array data

const Arr = [
  {
    name: 'setTitle',
    method: (title: string) => {
      return title;
    }
  },
  {
    name: 'getName',
    method: () => {
      return 'hello world';
    }
  }
];

I want get type like this

type Result = {
  setTitle: (title: string) => string;
  getName: () => string
}

How to derive it directly from typescript?

Upvotes: 1

Views: 46

Answers (1)

Tobias S.
Tobias S.

Reputation: 23925

You would have to use as const when declaring Arr to preserve the narrowed type information of the name properties.

const Arr = [
  {
    name: 'setTitle',
    method: (title: string) => {
      return title;
    }
  },
  {
    name: 'getName',
    method: () => {
      return 'hello world';
    }
  }
] as const;

Now the Result type can be constructed like this:

type Arr = typeof Arr

type Result = {
  -readonly [K in Arr[number] as K["name"]]: K["method"]
}

// type Result = {
//     setTitle: (title: string) => string;
//     getName: () => string;
// }

Playground

Upvotes: 1

Related Questions