【问题标题】:Typescript Error on Union type in generic : ' is not assignable to type'通用联合类型的打字稿错误:'不可分配给类型'
【发布时间】:2023-03-12 02:15:02
【问题描述】:

我有一个带有 Generic 的抽象类,我用 Union 类型实现,例如:

export abstract class DAO<T> { 
  async getDocument(ref: string): Promise<T> {
        // irrelevant code that return T asynchronously
  }
}

export class ConfigurationDAO extends DAO<ConfigurationType> {
 //...
}

export type ConfigurationType = 'advertising' | 'theming';

ConfigurationDAO 类的 getDocument() 签名是:

async getDocument(ref: string): Promise<ConfigurationType>

问题是当我调用这个函数时,我有一个错误:

const advertisingDocument: 'advertising' = await this.getDocument('advertising');

错误:

Type 'ConfigurationType' is not assignable to type '"advertising"'.
  Type '"theming"' is not assignable to type '"advertising"'

我不明白为什么当返回类型为'advertising' | 'theming''advertising'类型无效

【问题讨论】:

  • 解释为什么这不起作用,以及可能的解决方案:stackoverflow.com/a/51101237/197472
  • 感谢分享。我确实找到了解决方案。我终于通过类型转换分配了getDocument() 函数:const advertisingDocument: 'advertising' = await this.getDocument('advertising') as 'advertising'; 非常感谢

标签: javascript typescript generics casting union-types


【解决方案1】:

Typescript 会自动将您的 advertisingDocument 键入为 ConfigurationType,而您正试图以不同的方式强制键入它。
将其视为基本类型。
对于打字稿,您基本上是在做同样的事情:

const test: number = 'name';

因为'name' 是一个字符串,所以它不能分配给我声明为numbertest

希望对您有所帮助。

【讨论】:

  • 感谢您的解释! @Barryman9000 的回答帮助我找到了解决方案
猜你喜欢
  • 1970-01-01
  • 2018-02-02
  • 2021-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-29
  • 1970-01-01
  • 2018-08-01
相关资源
最近更新 更多