4

I have an object where all the keys are numbers and all the values are strings, like this:

var object = {
    1: "whatever",
    7: "whateverrr",
    ...
};

Is there any way I can write a TypeScript interface for this? I don't know what all the keys will be, but I do know that they will be numbers and that the values will be strings so I feel like it should be possible to do some kind of type checking.

1 Answer 1

16

You can use an index signature to represent this:

interface NumberToString {
    [n: number]: string;
}

var x: NumberToString;
x = { 1: 42 }; // Error
x[1].charAt(0); // OK

x['foo'] = 'bar'; // Still not an error, though
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! But why does it allow x['foo'] = 'bar';?
Long story, but basically because x[1] === x['1'], and x['hasOwnProperty'] is still valid
@Jeremy -Might want to read this Q & A: stackoverflow.com/questions/21960916/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.