2017-08-05 13 views
0

問題があります。Typescript Type 'string'はtype(enum)に割り当てられません

、列挙型の属性に列挙値を割り当てるエラー取得中:私は取得するべきではないと仮定Type 'string' is not assignable to type 'CountryCode'. は、属性と値の両方が同じenumタイプある原因を

enum属性を持つサービス:

@Injectable() 
export class UserData { 
    private _country_code: CountryCode; 
    private _currency_code: CurrencyCode; 

    constructor() { } 


    get country_code(): CountryCode { 
    return this._country_code; 
    } 

    set country_code(value: CountryCode) { 
    this._country_code = value; 
    } 
    get currency_code(): CurrencyCode { 
    return this._currency_code; 
    } 
    set currency_code(value: CurrencyCode) { 
    this._currency_code = value; 
    } 
} 

列挙

エラーと

の利用ケース:

this.userData.country_code = CountryCode[data.country_code]; 

答えて

0

data.country_codeはおそらくすでにタイプCountryCodeのある、したがって、this.userData.country_code = data.country_code;は十分なはずです。 CountryCode[...]を呼び出すと、整数と文字列表現の間の変換:

CountryCode[CountryCode["TH"] = 0] = "TH"; 
CountryCode[CountryCode["BGD"] = 1] = "BGD"; 

enum CountryCode {...}ためにコンパイルされたコードです。活字体で

1

列挙型は、プレーンなオブジェクトにtranspiledされています

name: CountryCode.TH <-- 0 (number) 
index: CountryCode[0] <-- 'TH' (string) 
           ^^^^^^^ 

後者はエラーをスローし、あなたが割り当てようとします

CountryCode[CountryCode["TH"] = 0] = "TH"; 
CountryCode[CountryCode["BGD"] = 1] = "BGD"; 

その次の、あなたがそれらを使用するかもしれない二つの方法がありそれをタイプ国コードの変数に変換します。だから私はこれがここで起こっていると信じています。 typescript playgroundでこの例を参照してください。

しかし、上記の出力を考えると、これは動作するはずです:

this.userData.country_code = data.country_code; 
OR 
this.userData.country_code = CountryCode[CountryCode[data.country_code]]; 

をしかし、後者はそのあまり意味がありません。

関連する問題