【问题标题】:Type 'ClassA<{ id: number; name: string; }>' is not assignable to type 'ClassA<Record<string, any>>'输入 'ClassA<{ id: number;名称:字符串; }>' 不能分配给类型 'ClassA<Record<string, any>>'
【发布时间】:2021-07-03 08:43:36
【问题描述】:

我有一个 ClassA,它应该只允许对象作为值类型。但是应该可以将您自己的对象类型作为泛型类型传递。通过Record&lt;string, any&gt;{ [key: string]: any } 完成。 一切正常。

但是一旦我尝试使用简单的条件类型提取 ClassA 泛型类型。

class ClassA<DataType = Record<string, any>>{
    public data: { [key: string]: ClassB<DataType> };
    constructor(){
      this.data = {};
    }
}

type NonArrayType<T> = T extends ClassA<infer U> ? U[] : never;

// Test function to test the 'NonArrayType' type
export function useWithoutArray<X extends ClassA>(
  deps: X
): NonArrayType<X> {
  return '' as any; // Doesn't matter
}

// Drops type error
const test6 = useWithoutArray(new ClassA<{ id: number; name: string }>()); 

我得到一个

Type 'ClassA<{ id: number; name: string; }>' is not assignable to type 'ClassA<Record<string, any>>'.

类型错误。在某种程度上它是有道理的,但理论上{ id: number; name: string; }Record&lt;string, any&gt;

连线的事情是它适用于 typescript playground.. 中的缩小示例,但不适用于我的框架

这是实际问题: https://github.com/agile-ts/agile/issues/76

谢谢

【问题讨论】:

  • 请分享可重现的代码。收藏?
  • 是的 sry .. Collection 我的意思是'classA'

标签: typescript conditional-statements typeerror typescript-generics


【解决方案1】:

它是固定在this playground 还是你的意思是别的?如果它是如此简单,那么不提供一个最小的可重复示例是一种耻辱,因为如果人们可以在那里看到错误,他们就可以投入其中。我不得不做很多想象你的意思。无论如何,下面没有编译错误。

class ClassA<T, V extends Record<string,T> = Record<string,T>> {
  constructor(readonly value:V){}
}

type NonArrayType<T> = T extends ClassA<infer U> ? U[] : never;

// Test function to test the 'NonArrayType' type
export function useWithoutArray<T,X extends ClassA<T>>(
  deps: X
): NonArrayType<X> {
  return '' as any; // Doesn't matter
}

// Drops type error
const test6 = useWithoutArray(new ClassA<any, { id: number; name: string }>({id:3,name:"john"})); 

【讨论】:

  • 是的..问题是..它在操场上工作(见问题,链接太长粘贴)很好..但在我的框架中它会丢弃错误和idk为什么..您的示例根本不起作用,因为它返回任何而不是{ id: number; name: string }[],但我想那是因为我正确描述问题的泄漏。谢谢
  • 有时我会遇到问题,如果我从某处随机获取 tsc 而不是使用我认为的 typescript 版本。最近的版本编译了旧版本没有的东西。
  • 是的,当然.. 可能值得一看.. 我花了一些时间配置这些,我以ES2015 为目标并使用commonjs 作为模块
  • 好的,我找到了一种解决方法,只需指定 useWithoutArray 函数从 ClassAClassA&lt;any&gt; 的值类型。现在打字稿很开心
猜你喜欢
  • 1970-01-01
  • 2023-01-18
  • 2021-06-12
  • 2022-10-15
  • 2021-07-02
  • 2021-08-19
  • 1970-01-01
  • 2022-12-06
  • 1970-01-01
相关资源
最近更新 更多