XYZ
XYZ

Reputation: 27387

How to defined interface for object with known and unknown property name

Here is an object I would love to define an interface for,

{
  date: '2000-10-01',
  foo: 10,
  bar: 11,
  baz: 12
}

The only thing I know is date property is always there but I do not know what other properties will be?

interface IProperty {
  date: string
  [option: string]: number
}

Does not seem to work in this case, TS complains that

string is not assignable to string index type number.

Upvotes: 1

Views: 464

Answers (1)

Fenton
Fenton

Reputation: 250812

In your original interface, you state that the interface will contain string indexes, and return a number - but your date property doesn't adhere to this, which means your interface contradicts itself.

You'll need to be honest about the fact you can get a number, or a string (in one specific case)...

interface IProperty {
  date: string
  [option: string]: string | number;
}

Upvotes: 2

Related Questions