简体   繁体   English

typescript 如何将泛型类型的键约束为仅字符串

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

I want a generic type OnlyStringKey<T> like below.我想要一个通用类型OnlyStringKey<T>如下所示。

   //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 :您可以将以下约束添加到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 .这将确保所有numbersymbol键只能具有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 }我不认为类型可以同时受到约束和通用,但您可能想要OnlyStringKey: Record<string, any> or OnlyStringKey:{ [key: string]: any }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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