1

Typescript lets me set an index type on a method signature like so:

function myFunc(dict: { [x: string]: string }) {
  ...
}

so this function will only accept objects that have string indicies and string values - akin to Dictionary<string, string> in C#. Can I restrict this further so that only objects that have a single string key with a string value are accepted?

i.e. so that

const a = {
  x: 'val'
};

is valid, but

const b = {
  x: 'val1',
  y: 'val2'
};

is not?

Obviously I can check the length of Object.keys() but it would be nice if the compiler could enforce it.

MaximilianMairinger
  • 2,176
  • 2
  • 15
  • 36
Mourndark
  • 2,526
  • 5
  • 28
  • 52
  • Are you sure you want to use a dictionary? Dictionaries are used when there's any number of properties in which names are not known in advance. Perhaps `function myFunc(key: string, value: string)` would do the trick just as well? – Karol Majewski Jun 11 '20 at 23:05
  • Possible duplicate of [typescript restrict number of object's properties](https://stackoverflow.com/questions/39190154/typescript-restrict-number-of-objects-properties) – jcalz Jun 12 '20 at 02:16

1 Answers1

1

I never like to say TypeScript can't do something, because...it's extremely powerful and there are a lot of obscure corners. :-) But I've never seen anything to suggest it can limit an indexed type to a single property.

Even if it can, though, I think in that situation I would use a [string, string], not an indexed type:

function example(tuple: [string, string]) {
    console.log(tuple[0], tuple[1]);
}

example(['x', 'val']); // works

example(['x', 'val', 'y', 'val']); // fails

Playground link

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875