Home > Mobile >  typescript How to constrain the key of a generic type to be string only
typescript How to constrain the key of a generic type to be string only

Time:09-21

I want a generic type OnlyStringKey<T> like below.

   //This line has no compile errors
    let x: OnlyStringKey<{whatEverJustString1: 1, whatEverJustString2: '' }>;
    
    //This line has error. Because key 2 is a number but a string
    let x: OnlyStringKey<{whatEverJustString1: 1, 2: '' }>;
    
    //This line has error too. Because key symbol.search is symbole but a string
    let x: OnlyStringKey<{whatEverJustString1: 1, [Symbol.search]: '' }>;

I have tried several method. And none of them works

CodePudding user response:

You can add the following constraint to OnlyStringKey:

type OnlyStringKey<
  T extends Record<string, any> & Record<number | symbol, never> 
> = T

This will make sure that all number and symbol keys can only have the type never.


Playground

CodePudding user response:

I don't think type can be constrained and be generic at the same time, but you may want something like OnlyStringKey: Record<string, any> or OnlyStringKey:{ [key: string]: any }

  • Related