Home > Enterprise >  Possibly incorrect type returned by 'keyof'
Possibly incorrect type returned by 'keyof'

Time:01-26

I am trying to define a type which will allow only strings to be used ask property keys. But strangely after creating such type and applying on it 'keyof' is not returning only string as possible type of the keys but rather string | number. Why ? is this a bug or check the example bellow.

So the question is why keyof is returning always string | number instead only string? How to get the correct type of the keys of StringKeysObject, which in my case is only string?

type StringKeysObject = {[key:string]:unknown};

const keys: keyof StringKeysObject = 123; // This should not be allowed since the keys can only be of type string but this is what keyof returns as possible types const keys: string | number

CodePudding user response:

You can use the utility Record<Keys, Type> instead of the object literal type, like this:

TS Playground

type StringKeysObject = Record<string, unknown>;

const key: keyof StringKeysObject = 123; /*
      ^^^
Type 'number' is not assignable to type 'string'.(2322) */

  •  Tags:  
  • Related