When the getData
function returns an object, we can assume that there is a key called item
in that object, which must be of type keyof Fruit
. If the type Fruit
has distinct keys defined, then keyof Fruit
represents a union type of each of those keys.
This return type is declared using an index signature.
For instance:
interface Fruit {
color: string;
tree: string;
}
type FruitKeys = keyof Fruit; // 'color'|'tree'
type Return = {
[item in FruitKeys]: any; // Index signature specifying how this type can be indexed.
}
const a : Return = {
color: 'aaa',
tree: null,
abc: '' // error because abc is not one of the keys of Fruit
}
A more concise way to define this would have been to use the Record
utility type. This alternative implementation looks like:
function getData(): Record<keyof Fruit, any> {
return {
color: [],
tree: [],
};
}
Playground link