typescript - 类型 'T' 不满足约束 'string | number | symbol' 。类型 'T' 不可分配给类型 'symbol'

标签 typescript

我有以下代码,但收到以下错误

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

我想知道如何修复泛型以便我可以传递一个联合记录

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

最佳答案

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

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>

关于typescript - 类型 'T' 不满足约束 'string | number | symbol' 。类型 'T' 不可分配给类型 'symbol',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64693643/

相关文章:

javascript - 如何从 VSCode 中的多个位置运行 Jest 测试

javascript - Angular 2 ajax加载并执行脚本标签

javascript - 如何更改图像的src

reactjs - 如何在 TypeScript 中动态更新类型对象上的键值对

javascript - Angular 中的重复功能失败

reactjs - Material 用户界面 : Concise way to to define styled Components?

javascript - TypeScript:类型 A 的索引键和类型 B 的保留键

typescript - VS代码: How to enable links in a webpage in the Webview

json - 如何在 JSON 数据的 Typescript 声明文件中使用破折号?

typescript - 从两个可区分的并集创建矩阵类型