简体   繁体   中英

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

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

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

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 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM