Reputation: 8246
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?
Upvotes: 1
Views: 650
Reputation: 3078
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: {}; }'
Upvotes: 2