TypeScript Version: 2.7.0
Code
type FruitName = "apple"|"pear";
interface IFruitInventory {
[key : FruitName] : number;
}
Expected behavior:
interface IFruitInventory {
[key : FruitName] : number;
}
Should be equivalent to
interface IFruitInventory {
apple? : number;
pear? : number;
}
Actual behavior:
Error : An index signature parameter type must be 'string' or 'number' when defining the _IFruitInventory_ interface.
It may be a duplicate, but I could not find another one with the same problem (most of the others I saw were about enums).
The syntax you鈥檙e looking for is
type IFruitInventory = {
[K in FruitName]: number
}
Or, if you want them to all be optional fields as you鈥檝e indicated,
type IFruitInventory = {
[K in FruitName]?: number
}
The first can also be expressed as Record<FruitName, number>, and the second by Partial<Record<FruitName, number>>.
My bad, thanks a lot.
Most helpful comment
The syntax you鈥檙e looking for is
Or, if you want them to all be optional fields as you鈥檝e indicated,
The first can also be expressed as
Record<FruitName, number>, and the second byPartial<Record<FruitName, number>>.