[英]Typescript Error on Union type in generic : ' is not assignable to type'
我有一个抽象的 class 和一个我用 Union 类型实现的 Generic,例如:
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
class 的getDocument()
签名是:
async getDocument(ref: string): Promise<ConfigurationType>
问题是,当我调用这个 function 时,出现错误:
const advertisingDocument: 'advertising' = await this.getDocument('advertising');
错误:
Type 'ConfigurationType' is not assignable to type '"advertising"'.
Type '"theming"' is not assignable to type '"advertising"'
我不明白为什么当返回类型为“广告”时'advertising'
类型无效'advertising' | 'theming'
'advertising' | 'theming'
Typescript 自动将您的advertisingDocument
键入为ConfigurationType
,而您正试图以不同的方式强制键入它。
把它想象成基本类型。
对于 typescript 你基本上做同样的事情:
const test: number = 'name';
因为那个'name'
是一个字符串,所以它不能分配给test
,我声明为一个number
。
希望它有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.