[英]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.