Mattia
Mattia

Reputation: 2281

Why does Typescript not narrow object keys to string

If I define a type like this:

type O = { [k: string]: any };

I would expect that keys in O would be narrowed to be of type string. However, if I define:

type KO = keyof O;

KO evaluates to string|number. Why is this? Didn't I explicitly narrow O's keys to be strings by stating [k:string] in my definition of O

Upvotes: 2

Views: 109

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249536

If you have a string index, you automatically get the number indexer as well as stated in the docs:

If you have a type with a string index signature, keyof T will be string | number (and not just string, since in JavaScript you can access an object property either by using strings (object['42']) or numbers (object[42])).

Upvotes: 2

Related Questions