2017-09-21 16 views
-1

typesの定数の参照方法は?例えば、私は、AとBのような定数値を下回る有しとして(私は後でtypescriptを使用して定数の型を定義する方法は?

const PATH = '@@test/'; 
export const A = `${PATH}A`; 
export const B = `${PATH}B`; 

export type Action = 
// UI actions 
{ type: typeof A, payload: { a: any } } 
| { type: B, payload: { b: boolean }} 

//使用

const id = (state= initialState, action: Action) => { 
    const nextState = state; 
    switch (action.type) { 
     case A: { 
      const{a} = action.payload; 
      break; 
     } 
     case B: { 
      const { b} = action.payload; 
     break; 
     } 
     default: 
      break; 
    } 

答えて

0

活字体現在switch caseにアクションタイプを使用することができるアクションタイプを作成する必要がありますv2.5の)は、concatenate string literal typesの能力を欠いています。 TypeScriptで2つの文字列リテラルを連結すると、結果の型はstringのみとなります。例えば、それは以下のが正しいという考えを持っていない:

export const A = `${PATH}A`; // inferred as string 
export const B = `${PATH}B`; // inferred as string 

したがって、Actionはと考えていない:あなたのケースでは

const x = "x"; 
const xx: "xx" = x + x; // error! 

、活字体はstring値であることがABを推論します

export type Action = 
    { type: typeof A, payload: { a: any } } | 
    { type: typeof B, payload: { b: boolean } } 
type性は両方の場合で同じであるため discriminated unionこと

ABのリテラルタイプを手動で指定するための唯一の方法です。実行時チェックを使用して、定数を誤って構成していないかどうかを確認することができます。はい、それはunfortunateだが、それは動作します:今すぐ

const PATH = '@@test/'; 
export const A = "@@test/A"; 
export const B = "@@test/B"; 
if (!A.startsWith(PATH) || !B.startsWith(PATH)) { 
    throw new Error("Bad configuration"); 
} 

Actionが適切区別組合であり、あなたがtype財産上のswitch、活字体は自動的にあなたのための型を狭めるますとき:

declare const action: Action; 
switch (action.type) { 
    case A: { 
    const { a } = action.payload; // okay 
    break; 
    } 
    case B: { 
    const { b } = action.payload; // okay 
    break; 
    } 
    default: 
    const assertNever: never = action; // okay 
    break; 
} 

希望に役立ちます。がんばろう!

関連する問題