2017-12-17 14 views
2

私は以下のような型スクリプトを持っています。要素は暗黙のうちに 'any'型を持っています。なぜなら、インデックス式が列挙型の列挙型ではなく数値型の 'number'であるからです。

enum Categories { 
    textbox = 1, 
    password 
} 

let typedata:string ="textbox"; 
let enumdata:Categories; 

このテキストボックス文字列をenumに変換します。私はそれをenumdata変数に割り当てることができます。私は

enumdata=Categories[typedata] 

を使用してこれを行うにしようとしたとき、私はエラーにインデックス式がタイプではないので、

要素が暗黙のうちに「あらゆる」タイプを持っている「数」は

を得ている私を聞かせてください。誰かがこの問題に直面したかどうかを知る。このための解決策を見つけたら、私に例を教えてください。

マイtypescriptですバージョンは

{ 
    "compilerOptions": { 
     "module": "commonjs", 
     "target": "es6", 
     "lib": [ 
     "dom", 
     "es2015" 
     ], 
     "noImplicitAny": false, 
     "sourceMap": true, 
     "rootDir": "src", 
     "outDir": "dist", 
     "noEmitOnError": true 
    } 
} 

はtypescriptですであなたに Vipin

答えて

1

ありがとうござい2.6.2

tsconfig.jsonで、列挙型は、数と正確なプロパティ名によってのみインデックス可能です。

"textbox"又はnumberのタイプの識別子textbox又は0を期待するが、文字列の型として、その値を受信します。

これを回避するには、適切なプロパティ名が対応する列挙型の値を取得するために使用されることを保証する型を宣言できます。例えば:罰金シェーンバンがBogaardデン取り組んでいる

enum Categories { 
    textbox = 1, 
    password 
} 

declare type CategoryType = keyof typeof Categories; 

const getCategory = (key: CategoryType) => Categories[key]; 
/* The following will work as well, but does not ensure the correct typecheck when calling the function. 
    However you can keep you 'typedata' field as type of string. */ 
// const getCategory = (key: string) => Categories[key as CategoryType]; 

let enumdata: Categories; 
const typedata: CategoryType = "textbox"; 

enumdata = getCategory(typedata); 

...または単に

const typedata: string = "textbox"; 
enumdata = Categories[typedata as CategoryType]; 
+0

感謝を。 – Vipin

関連する問題