Reputation: 21
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
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;
// }
Upvotes: 1