Typescript: An index signature cannot be a union of strings

Created on 6 Nov 2017  路  2Comments  路  Source: microsoft/TypeScript




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).

Most helpful comment

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>>.

All 2 comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

blendsdk picture blendsdk  路  3Comments

siddjain picture siddjain  路  3Comments

zhuravlikjb picture zhuravlikjb  路  3Comments

MartynasZilinskas picture MartynasZilinskas  路  3Comments

Roam-Cooper picture Roam-Cooper  路  3Comments