2017-06-01 7 views
0

ReactプロジェクトをTypeScriptに変換していますが、Iconコンポーネントは文字列ですが有効なCSSクラス名。インポートされたオブジェクトに基づいて有効な文字列を設定する/プログラムで文字列リテラルタイプを作成する

私はこれを取り扱う方法リアクトのPropTypesは

Icon.propTypes = { 
    icon: oneOf(Object.keys(css)).isRequired, 
} 

このような文字列リテラルの型では、すべてのクラス名を入力することなく、活字体で同じことを達成するための方法はありましたか?あなたのcssオブジェクトのようなものであれば

interface Props { 
    icon: "class1" | "class2" | ... 
} 

答えて

1

は:

interface Props { 
    icon: keyof typeof css 
} 

// fine: 
let props: Props = { 
    icon: "class1" 
} 

しかし、この:エラーで

let props: Props = { 
    icon: "something else" 
} 

結果:

const css = { 
    "class1": "something", 
    "class2": "something", 
    "classN": "something" 
} 

その後、あなたはこれを行うことができます

Type '{ icon: "something else"; }' is not assignable to type 'Props'.
Types of property 'icon' are incompatible.
Type '"something else"' is not assignable to type '"class1" | "class2" | "classN"'.

関連する問題