1

It's better to show code example than try to explain it:

type MyType = {[key: string]: string;}
let v: MyType = {
 propOne: "one",
 propTwo: "two"
}; // Why is there no error?

Why does the TS interpreter not throw an error here? As you see, the MyType object should be an object with one property. But I could define the MyType object with two properties.

In general: How is it possible to specify an allowable number of properties? (maybe using index signatures or some similar approach). To be more precise, how is it possible to typify such two objects:

let o1 = {
 singlePropertyWithRandomName: "abcd"
};

let o2 = {
 propertyWithRandomNameOne: "abcd",
 propertyWithRandomNameTwo: "efgh",
 ...,
 propertyWithRandomNameThousand: "xyz",
};
LeoDog896
  • 3,472
  • 1
  • 15
  • 40
Volodymyr Nabok
  • 415
  • 1
  • 4
  • 11
  • 1
    `[key: string]: string;` is an index signature... this means the obkject ca have any number of properties it's juts that they need to be a `string` – Titian Cernicova-Dragomir Oct 21 '22 at 09:09
  • 1
    There is no TypeScript type that can do that. There can be any number of properties when you have an index signature. You could possibly use a generic function to validate such object types. – Tobias S. Oct 21 '22 at 09:10
  • 1
    There's no easy way to specify "an object type with exactly one property", although the linked questions/answers explore various non-easy workarounds. Good luck! – jcalz Oct 21 '22 at 13:41

0 Answers0