2017-08-26 68 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'); 
相关问题