Reputation: 1893
I found this TypeScript construct in the source code of a colleague:
protected getData(): { [item in keyof Fruit]: any; } {
return {
color: [],
tree: [],
};
}
I don't understand the return-type definition in the signature: { [item in keyof Fruit]: any; }
What does this mean?
Upvotes: 0
Views: 30
Reputation: 40690
getData
returns an object. If we assume that there's a key in that object named item
then item
must be in
the type keyof Fruit
. If the type Fruit
has distinct keys defined then the type keyof Fruit
is a union type of each of those keys.
The way this return type is defined uses an index signature type
For example:
interface Fruit {
color: string;
tree: string;
}
type FruitKeys = keyof Fruit; // 'color'|'tree'
type Return = {
// item is either 'color' or 'tree'
[item in FruitKeys]: any; // This is an index signature defining how this type can be indexed.
}
const a : Return = {
color: 'aaa',
tree: null,
abc: '' // error abc not in the keys of Fruit
}
A shorter way of defining this would have been to use the Record
utility type. In this case it's shorter to write:
function getData(): Record<keyof Fruit, any> {
return {
color: [],
tree: [],
};
}
Upvotes: 2