我有以下代码,但收到以下错误
类型 '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/