2017-08-26 63 views
0

我一直在玩最近的TypeScript,字符串文字很適合Redux動作和縮減器。例如:如何在TypeScript中輸入導入的redux動作?

const INCREMENT = "INCREMENT"; 
type INCREMENT = typeof INCREMENT; 

const DECREMENT = "DECREMENT"; 
type DECREMENT = typeof DECREMENT; 

interface IncrementAction { 
    type: INCREMENT; 
} 
interface DecrementAction { 
    type: DECREMENT; 
} 

type Actions = IncrementAction | DecrementAction; 

const reducer = (state = 0, action: Actions) => { 
    switch (action.type) { 
    case INCREMENT: 
     return state + 1; 
    case DECREMENT: 
     return state + 1; 
    default: 
     return state; 
    } 
}; 

我偶然發現的問題是,輸入動作名稱是從npm模塊導入的。因此,如果沒有任何類型,代碼將如下所示:

import { SOME_ACTION } from 'npm-packaged-with-actions'; 

const reducer = (state = null, action) => { 
    switch (action.type) { 
    case SOME_ACTION: 
     return state + 1; 
    default: 
     return state; 
    } 
} 

如何爲SOME_ACTION定義TypesScript類型?類型定義文件出口SOME_ACTION作爲一個字符串,所以我不能創建類型爲:

type SOME_ACTION = typeof SOME_ACTION; 

在這種情況下SOME_ACTION是一個字符串類型,而不是一個字符串,因此減速動作匹配不起作用。

回答

0

您可以指示編譯器爲您的代碼生成定義文件,然後爲模塊提供定義。這樣做當您導入模塊時,編譯器將知道您在Typescript中定義的類型。關於打字稿寫NPM模塊

"compilerOptions": { 
    "module": "commonjs", 
    "declaration": true 
} 

的更多信息,你可以找到關於this問題

0

創建Redux的行動打字稿是類型守衛一個非常簡單的方法。 This package通過使用提供的類型輸入名爲「有效負載」的操作,以簡單的方式完成。

所以你定義你的行動

export const ActionA = defineAction<{ url: string }>('Action A'); 

// And you can dispatch the action as 
dispatch(ActionA.get({ url: 'http://www.googlel.com' }); 

但是從另一個模塊來的動作,你可以這樣做:

import { SOME_ACTION } from 'npm-packaged-with-actions'; 

// And you'll have an action based on the provided types 
export const ActionOfModule = defineAction</* your desire type here */string>(SOME_ACTION); 

// But again to this is an action creator, so to get the action you need to call "get" or "strictGet" from it 
dispatch(ActionOfModule.strictGet('This is the payload of this action');