簡體   English   中英

TypeScript通用類:無法分配給通用類型變量

[英]TypeScript Generic Classes: Cannot assign to Generic Type Variable

我正在嘗試為我的班級使用通用接口。 我的班級有一個可擴展接口的通用類型和一個具有該類型的類變量。 但是,一旦我嘗試為該變量賦值,編譯器就會給我一個錯誤(示例:A類)

當我不擴展泛型類型時,它將起作用。 (例如:B級)

//Generic Classes problem
interface MyStateInterface {
    test?: number
}

class A<IState extends MyStateInterface> {
    protected state: IState;

    constructor() {
        // Error here
        this.state = {
            test: 1
        };
    }
}

class B<IState extends MyStateInterface> {
    protected state: MyStateInterface;

    constructor() {
        this.state = {
            test: 1
        };
    }
}

有誰能解決這個問題?

class A<IState extends MyStateInterface> {
    protected state: IState;

    constructor() {
        this.state = { ...

您所說的是IState 擴展了 MyStateInterface 這意味着某人可以使用比MyStateInterface 更具體的類型實例化A 具體來說,有人可以添加新的必需屬性:

interface MyCoolState extends MyStateInterface {
  required: string;
}
let x = new A<MyCoolState>();

發生這種情況時,您的構造函數代碼通過使用缺少required的值初始化state打破MyCoolState的約定。

您如何解決此問題取決於您要執行的操作。 通常,當人們發現自己處在這種情況下時,正確的做法是根本不要泛型-子類使用派生性更高的類型覆蓋state 已經是合法的,因此,如果這是您要嘗試啟用的行為,根本不需要泛型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM