1

I have this very simple code:

let viewsDictionary: { [key: string]: Object } = {
    abc: {}
};
type ViewName = keyof typeof viewsDictionary;

let result: ViewName;

result = "category";

TypeScript version 2.2.2 does not complain that result can only have the value "abc". Why?

1
  • Are you sure you mean Object with an uppercase O? Commented May 4, 2017 at 5:00

1 Answer 1

2

You are explicitly giving viewsDictionary type { [key: string]: Object }. The fact that you are assigning a compatible value does not change its type and so typeof viewsDictionary stays { [key: string]: Object } and keyof are any string.

You can verify that by assigning

viewsDictionary = { category: {} };

which works fine as well.

Just remove the explicit type declaration, so TS infers the type itself and it will work as expected:

let viewsDictionary = {
    abc: {}
};
type ViewName = keyof typeof viewsDictionary;

let result: ViewName;

result = "category"; error

now complains that Type '"category"' is not assignable to type '"abc"'.

Update:

You can also specify the type explicitly (from comments):

let viewsDictionary: {abc: {}} = {
    abc: {},
    def: {}, // error 
};
type ViewName = keyof typeof viewsDictionary;

let result: ViewName;

result = "def"; // still error

This will complain when you add another key to viewsDictionary that Type '{ abc: {}; def: {}; }' is not assignable to type '{ abc: {}; }'

Sign up to request clarification or add additional context in comments.

1 Comment

I thought as much; the technical term for this is type widening. But if I do as you say, problem now is that viewsDictionary itself can have values of any type. I want to ensure that the values of viewsDictionary are all of a specific type, and also create a type off of its keys.

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.