weiceshi
weiceshi

Reputation: 25

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

Upvotes: 0

Views: 51

Answers (2)

Tim Woohoo
Tim Woohoo

Reputation: 562

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 }

Upvotes: 0

Tobias S.
Tobias S.

Reputation: 23825

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

Upvotes: 1

Related Questions