1

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?

1

1 Answer 1

1

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

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.