简体   繁体   中英

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM