2017-09-08 24 views
1

定義平板類像這樣工作得很好:如何定義類變量不平整,使用默認值

class Test { 
 
company_name: string = ""; 
 
company_id: number = 0; 
 
company_website: string = ""; 
 
}

如果我做let product = new Test()這一切按預期工作,和product也加載了默認值。

我該如何實現同樣的事情,但是對於不平坦的類變量呢?理想的情況下它應該工作像在這個例子中(其中失敗):

class Test { 
 
    companyData: { 
 
    company_name: string = ""; 
 
    company_id: number = 0; 
 
    company_website: string = ""; 
 
    } 
 
    productData: { 
 
    category_id: number = 0; 
 
    product_name: string = ""; 
 
    price: { 
 
     price_in: number = 0; 
 
     price_out: number = 0; 
 
    } 
 
    } 
 
}

的錯誤VSCode爲A type literal property cannot have an initializer。在我的用例中,重要的是設置所有變量,並且可以將它們分配爲默認值。

回答

2

您正在定義Types,而不是設置propertiesvalues(或介於兩者之間,語法無論如何都是錯誤的)。如果你也想擁有它們Typed(你應該),使用的界面

class Test { 
    public companyData = { 
    company_name: '', 
    company_id: 0, 
    company_website: '' 
    }; 
    public productData = { 
    category_id: 0, 
    product_name: '', 
    price: { 
     price_in: 0, 
     price_out: 0 
    } 
    }; 
} 

interface CompanyData { 
    company_name: string; 
    company_id: number; 
    company_website: string; 
} 

interface ProductData { 
    category_id: number; 
    product_name: string; 
    price: Price; 
} 

interface Price { 
    price_in: number; 
    price_out: number; 
} 

class Test { 
    public companyData: CompanyData = { 
    company_name: '', 
    company_id: 0, 
    company_website: '' 
    }; 
    public productData: ProductData = { 
    category_id: 0, 
    product_name: '', 
    price: { 
     price_in: 0, 
     price_out: 0 
    } 
    }; 
} 

試試這個

相關問題