类型'T'不满足约束'string |编号|符号'。类型“ T”不可分配给类型“符号”

时间:2020-11-05 08:30:30

标签: typescript

我有以下代码,并且收到以下错误

Type 'T' does not satisfy the constraint 'string | number | symbol'. Type 'T' is not assignable to type 'symbol'.

我想知道如何修复通用名称,以便通过联合记录

   export type Project<T> = Readonly<{
      dirs: Record<T, string>
      setup: () => Promise<string>
    }>
    
    type Dirs = 'a' | 'b' | 'c'
    
    type Start = Project<Dirs>

1 个答案:

答案 0 :(得分:2)

如果您需要此约束,则只需添加它。也许您甚至可以使其更具限制性(例如,删除符号):

export type Project<T extends string | number | symbol> = Readonly<{
      dirs: Record<T, string>
      setup: () => Promise<string>
    }>
    
    type Dirs = 'a' | 'b' | 'c'
    
    type Start = Project<Dirs>

也请注意,我不知道您想对Record<T, string>做什么。 Record用于仅将某些键保留在给定的对象类型中。您实际上是指dirs: T吗?如果是这样,您可以这样做:

export type Project<T extends string> = Readonly<{
      dirs: T
      setup: () => Promise<string>
    }>
    
    type Dirs = 'a' | 'b' | 'c'
    
    type Start = Project<Dirs>